看到两个字符串是通过递归相互反射

时间:2014-07-17 05:56:42

标签: java string recursion

我的代码用于获取两个字符串,并在忽略大小写时查看它们是否是彼此的直接反映。例如,isReverse(" abC"," cBA")应返回true,而isReverse(" abde"," aedb")返回false。

我无法确定它们是否是反射。为什么递归情况不起作用?我是递归编程的新手,这是一个非常大的挑战。

    public static void main(String[] args) {
        String first = "abadcd";
        String second = "Dcdbua";
        System.out.println(isReverse(first, second));
    }

    public static boolean isReverse(String first, String second) {
        if (first.length() != second.length()) { // If string are not of equal length, impossible to be reverses
            return false;
        }

        String check1 = "" + first.charAt(first.length() - 1);
        String check2 = "" + second.charAt(0);
        if (check1.equalsIgnoreCase(check2)) { // gets the 1st char of first and last char of 2nd to see if it matches
            String temp1 = first.substring(1,first.length()-1); // shorten the string by escluding first char
            String temp2 = second.substring(0, second.length()-2); // shorten the string by last char
            isReverse(temp1, temp2);
        } 
        return true; // reaches here after goes through 
    } 

2 个答案:

答案 0 :(得分:0)

这里有很多问题。

  1. 您对子字符串调用的索引不正确。
  2. 你的递归调用是不正确的:递归调用isReverse就是这样做的 具有回报价值的东西;你忽略了它。
  3. 您没有“正常”终止案例,您决定返回true(您确实有“返回true”,但请参阅(2)。

答案 1 :(得分:0)

您的代码中存在多个问题。

  • 你错过了递归。您需要在isReverse方法中返回对isReverse的调用。
  • 您需要成功终止(如果长度均为0,则字符串彼此相反)
  • 您使用的子串索引不是很好
  • 你在char comparaison和substrings之间反转你的字符串
  • 除了停止状态外,您需要在任何地方返回false

      public static void main(String[] args)
      {
        String first = "abadcd";
        String second = "Dcdbua";
        String third = "dcdabA";
        System.out.println("Should be false = " + isReverse(first, second));
        System.out.println("Should be true = " + isReverse(first, third));
      }
    
      public static boolean isReverse(String first, String second)
      {
        System.out.println("1=" + first + " / 2=" + second);
        if (first.length() != second.length())
        { // If string are not of equal length, impossible to be reverses
          return false;
        }
    
        // Stopping condition
        if (first.length() == 0 && second.length() == 0)
        {
          return true;
        }
    
        String check1 = "" + first.charAt(first.length() - 1);
        String check2 = "" + second.charAt(0);
        if (check1.equalsIgnoreCase(check2))
        { // gets the 1st char of first and last char of 2nd to see if it matches
          String temp1 = first.substring(0, first.length() - 1); // shorten the string by escluding first char
          String temp2 = second.substring(1, second.length()); // shorten the string by last char
    
          return isReverse(temp1, temp2);
        }
        return false; // reaches here after goes through
      }