所以我的程序是关于语言L = {'w$w' : w
可能是$, w' = reverse(w)}
所以当hod $ doh之类的东西被输入到isINlanguage函数的参数时,它应该返回true,但我的程序只是停止并且挂起并没有放任何东西
import java.util.Stack;
public class Stacks
{
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;
}
}
}
答案 0 :(得分:2)
您没有将ch
循环中的while
重置为下一个字符:
while (ch != '$') {
aStack.push(ch);
i++;
ch = aString.charAt(i); // Add this
}
此外,在try
区块内,不需要演员表。作业:
stackTop = (char) aStack.pop();
...写得更好:
stackTop = aStack.pop();
boolean
变量和try-catch
块,您确实使任务变得复杂。不要让stack.pop()
抛出任何异常。相反,仅当stack不为空时才弹出元素。此外,一旦发现字符串与所需语言不匹配,您就可以直接返回,因此不需要布尔变量。
我会将您的方法修改为:
static boolean isInLanguage(String aString){
Stack<Character> aStack = new Stack<>();
int i = 0;
char ch;
// This is simplified way to write your first while loop
// Read a character, move the index further, and test, all in single statement
while ((ch = aString.charAt(i++)) != '$') {
aStack.push(ch);
}
// Iterate till the stack is not empty
while (!aStack.isEmpty()) {
// Get next character in string, and pop an element from stack
// If they are not equal, return false
if (aString.charAt(i++) != aStack.pop()) {
return false;
}
}
// If we reach here, means stack is empty. Test if the index `i` has reached end of the string.
// If it reached the end of the string, return true, else return false (because there are still some characters to be processed).
return i == aString.length();
}
aString.charAt(i++)
将获取索引i
处的字符,然后再增加i
。