我正在尝试实现一种算法“以一种语言识别字符串”
L = {'w$w' : w 是一个可能的空字符串,除了 $, w' = reverse(w)}
我收到一条错误消息ch = aString[i];
:表达式的类型必须是数组类型,但解析为字符串
也在哪里,stackTop = aStack.pop();
但在这里,它要求转换为 char
' 导入 java.util.Stack;
公共类堆栈{
public static void main(String[] args){
boolean eval = isInLanguage("sod$dos");
System.out.println(eval);
}
static // astack.createStack();
boolean isInLanguage(String aString){
Stack<Character> aStack = new Stack<>();
int i = 0;
char ch = aString.charAt(i);
while (ch != '$') {
aStack.push(ch);
i++;
}
//Skip the $
++i;
// match the reverse of w
boolean inLanguage = true; // assume string is in language
while (inLanguage && i < aString.length()) {
char stackTop;
ch = aString.charAt(i);;
try {
stackTop = (char) aStack.pop();
if (stackTop == ch) {
i++;
} else {
// top of stack is not ch(Charecter do not match)
inLanguage = false; // reject string
}
} catch (StackException e) {
// aStack.poo() failed, astack is empty (first, half of Stirng
// is short than second half)
inLanguage = false;
}
}
if (inLanguage && aStack.isEmpty()) {
return true;
}
else{
return false;
}
}
}
'
我刚刚进行了必要的更改,但现在,它会编译,但它似乎并没有停止,也没有输出任何东西,我期待控制台中有一个 true