【问题标题】:Java Palindrome (Boolean Method) with iterative solution (while loop)具有迭代解决方案(while 循环)的 Java Palindrome(布尔方法)
【发布时间】:2015-11-23 05:28:55
【问题描述】:

为什么我的回文程序不能正常工作?它总是返回false,我不知道为什么。

这是我的代码:

public static boolean isPalindromIterative(String string) {
    int a = 0;
    int b = string.length() - 1;        
    while (b > a) {
        if (a != b) {            
            return false;
        }
        a++;
        b--;        
    }
    return true;
}

【问题讨论】:

    标签: java iteration palindrome


    【解决方案1】:

    您正在比较 a 和 b 的值,当您开始比较时它们并不相同,因此您从方法中得到错误。

    在你的if条件下,改为string.charAt(a) != string.chatAt(b)

    【讨论】:

    • 是的,帮了我 :) 谢谢 :/ 现在我觉得自己很笨 :D 非常感谢
    【解决方案2】:

    当你说

    while (b > a) {
        if (a != b) {
    

    很明显a 不等于b(否则不会进入循环)。根据上下文,我相信您想比较 String 中的字符。我会使用String.toCharArray() 来获取char[] 并执行类似的操作

    char[] chars = string.toCharArray();
    while (b > a) {
        if (chars[a] != chars[b]) {
    

    【讨论】:

      【解决方案3】:

      如果您的代码while (b > a) 中的b > a,那么a 不等于您的代码if (a != b) 中的b

      【讨论】:

        【解决方案4】:

        在java中检查给定字符串是否为回文,只需使用StringBuilderreverse()方法并检查给定字符串。

            public static boolean isPalindromIterativeStringBuilder(String string) {
                    StringBuilder sb = new StringBuilder(string);
                    sb.reverse(); //Reverse to the given string
                    return sb.toString().equalsIgnoreCase(string); //Check whether given string is equal to reverse string or not
           }
        

        【讨论】:

          【解决方案5】:

          这也是一种迭代方法。 如果我帮助了某人,我会很高兴。 ;)

          public static boolean isPalindromeIterative(String string) {
          String polindromCheck = string.toUpperCase();
          for (int index = 0; index < polindromCheck.length(); index++) {
            if (polindromCheck.charAt(index) != polindromCheck.charAt(string.length() - 1 - index)) {
              return false;
            }
          }
          return true;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-12-26
            • 1970-01-01
            • 2013-07-22
            • 1970-01-01
            • 1970-01-01
            • 2017-09-12
            相关资源
            最近更新 更多