gpt4 book ai didi

java - 使用堆栈的回文

转载 作者:行者123 更新时间:2023-11-30 07:55:56 24 4
gpt4 key购买 nike

我用java中的栈写了一个回文。但是,由于某种原因,在弹出堆栈时,程序无法按预期工作。我还尝试过使用 top 并使用此变量进行迭代。不管怎样,它都不起作用。

import java.util.Stack;

class Palindromer {

Stack<Character> stack = null;
int top = -1;

public boolean isPalindrome(String s) {
for (int i = 0; i < s.length(); i++) {
stack = new Stack<Character>();
stack.push(s.charAt(i));
top++;
}

System.out.println("value of top is " + top);
String returnString = "";

while (!stack.isEmpty()) {
returnString += stack.pop();
}
System.out.println(returnString);

return returnString.equals(s);
}
}

public class PalindromeChecker {
public static void main(String[] args) {
Palindromer palin = new Palindromer();
if (palin.isPalindrome("BananaB")) {
System.out.println("is palindrome");
} else {
System.out.println("not a palindrome");
}
}
}

最佳答案

您应该放置 new Stack<Character>();在循环之外。

你的做法:

    for (int i = 0; i < s.length(); i++) {
stack = new Stack<Character>();
stack.push(s.charAt(i));
top++;
}

stack变量在每次循环时都会重新分配,并且在循环后仅包含一个字符。改成

    stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
top++;
}

顺便说一句:最好声明stacktopisPalindrome方法。所以你摆脱了 top 中的错误进一步通话。

关于java - 使用堆栈的回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668688/

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