回文失败

问题描述 投票:0回答:1

你好(我的第一篇文章,我应该编写一个程序,检查句子或单词是否是回文。为此,我应该无缘无故地使用堆栈。事实是,我在控制台中打印了两个解决方案,但即使它们相同,它也会返回false

我的代码:

  // Test if text is a palindrome.
  // Ignore upper/lower case, white space, and punctuation.
  //
  public static boolean isPalindrome(String text) {
    boolean ispalin =false;
    char tmp;
    String temp = text;
    String text2 = "";
    String check = "";
    Stack<Character> stacktext = new Stack<Character>();
    Stack<Character> stackcheck = new Stack<Character>();
    text = text.toLowerCase();



    for (int j = 0; j < text.length(); j++) {
      if(     text.charAt(j) != ' '&&
              text.charAt(j) != ','&&
              text.charAt(j) != '?'&&
              text.charAt(j) != '.'&&   //delete some symbols
              text.charAt(j) != '!'&&
              text.charAt(j) != '-'){


        tmp = text.charAt(j);
        text2 += tmp;
      }
    }



    for (int j = text.length()-1; j > -1; j--) {
      if(     text.charAt(j) != ' '&&
              text.charAt(j) != ','&&
              text.charAt(j) != '?'&&
              text.charAt(j) != '.'&&
              text.charAt(j) != '!'&&
              text.charAt(j) != '-'){


        tmp = text.charAt(j);
        check += tmp;
      }
    }
    for (int i = 0; i < text2.length(); i++) {
      stacktext.push(text2.charAt(i));
    }
    for (int i = check.length()-1; i != -1; i--) {
      stackcheck.push(check.charAt(i));
    }
    System.out.println(stackcheck);
    System.out.println(stacktext);
    if (stackcheck == stacktext) return true;
    else return false;
  }


  public static void main(String[] args) {
    System.out.println(isPalindrome("Na, Fakir, Paprika-Fan?"));
  }
}

输出:

[n, a, f, a, k, i, r, p, a, p, r, i, k, a, f, a, n]
[n, a, f, a, k, i, r, p, a, p, r, i, k, a, f, a, n]
false
java palindrome
1个回答
1
投票

您比较

//...
if (stackcheck == stacktext) return true;
    else return false;
//...

不是您想要的,这些是不同的对象,它将始终评估为false。

您需要:

//...
if (stackcheck.equals(stacktext)) return true;
    else return false;
//

或者更好:

//...
return stackcheck.equals(stacktext);
//...
© www.soinside.com 2019 - 2024. All rights reserved.