gpt4 book ai didi

java - 处理语言、java程序中识别字符串的堆栈

转载 作者:行者123 更新时间:2023-12-02 06:39:16 25 4
gpt4 key购买 nike

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

}
}
}

最佳答案

您没有将 while 循环内的 ch 重置为下一个字符:

while (ch != '$') {
aStack.push(ch);
i++;
ch = aString.charAt(i); // Add this
}

此外,在 try block 内,不需要进行强制转换。作业:

stackTop =  (char) aStack.pop();  

...最好写成:

stackTop = aStack.pop();
<小时/>

顺便说一句,通过使用 boolean 变量和 try-catch block ,您的任务确实变得复杂了。不要让 stack.pop() 抛出任何异常。相反,仅当堆栈不为空时才弹出元素。而且,一旦发现字符串与所需的语言不匹配,就可以直接返回,因此不需要 boolean 变量。

我会将你的方法修改为:

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

关于java - 处理语言、java程序中识别字符串的堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19326508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com