RecognizedString C++ Algorithm Hi, I need help creating this function. I have a
ID: 3733202 • Letter: R
Question
RecognizedString C++ Algorithm
Hi, I need help creating this function. I have a pseudo-code but I can't get it running in a function, can someone help me?
Here is the pseudo-code:
// Checks the string aString to verify that it is in language L.
// Returns true if aString is in L, false otherwise.
recognizeString(aString: string): boolean
aStack = a new empty stack
// Push the characters that are before the $ (that is, the characters in s) onto the stack
i = 0
ch = character at position i in aString
while (ch is not a '$')
{
aStack.push(ch)
i++
ch = character at position i in aString
}
// Skip the $
i++
// Match the reverse of s
inLanguage = true // Assume string is in language
while (inLanguage and i < length of aString)
{
if (!aStack.isEmpty())
{
stackTop = aStack.peek()
aStack.pop()
ch = character at position i in aString
if (stackTop equals ch)
i++ // Characters match
else
inLanguage = false // Characters do not match (top of stack is not ch )
}
else
inLanguage = false // Stack is empty (first half of string is shorter
// than second half)
}
if (inLanguage and aStack.isEmpty())
aString is in language
else
aString is not in language
Explanation / Answer
#include <iostream>
#include <stack>
using namespace std;
void recognizeString(string str) {
stack<char> stack;
int i=0;
while(str[i] != '$') {
stack.push(str[i]);
i++;
}
// Skip the $
i++;
bool inLanguage = true;
while (inLanguage && i < str.length()){
if (!stack.empty()){
char stackTop = stack.top();
stack.pop();
char ch = str[i];
if (stackTop == ch)
i++; // Characters match
else
inLanguage = false; // Characters do not match (top of stack is not ch )
}else
inLanguage = false; // Stack is empty (first half of string is shorter
// than second half)
}
if (inLanguage && stack.empty())
cout<<"aString is in language"<<endl;
else
cout<<"aString is not in language"<<endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.