0

所以我的程序是关于语言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;

    }
}
}
4

1 回答 1

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()抛出任何异常。相反,仅当堆栈不为空时才弹出元素。此外,您可以在发现字符串与所需语言不匹配时直接返回,因此不需要布尔变量。

我会将您的方法修改为:

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++)将在 index 处获取字符i,然后递增i

于 2013-10-11T20:17:05.267 回答