【问题标题】:Convert String to Reverse String Using Recursion in Java在 Java 中使用递归将字符串转换为反向字符串
【发布时间】:2020-02-17 21:06:38
【问题描述】:

今天我正在尝试将字符串转换为反向字符串e.g(Cat Is Running into Running Is Cat) 逐字不是字符

public class ReverseString_ {
    public static void reverse(String str) {
        String[] a = str.split(" ");
        for (int i = a.length - 1; i >= 0; i--) {
            System.out.println(a[i] + " ");
        }
    }

    public static void main(String[] args) {
        reverse("Cat Is Running");
    }
}

显示以下输出:

Running Is Cat BUILD SUCCESSFUL (total time: 0 seconds)

我正在尝试将字符串转换为与上面相同的反向字符串,但通过递归方法,但这似乎太混乱了。并显示更多错误。有人可以帮我理解它。非常感谢

public static String reverse_recursion(String str) {
    if (str == null)
        return null;
    else {
        String Arry[] = str.split(" ");
        int n = Arry.length - 1;
        System.out.println(Arry[n] + "");
        return reverse_recursion(Arry[n - 1]);
    }
}

public static void main(String[] args) {
    reverse_recursion("Cat Is Running");
}

此代码显示以下输出:

Running
Is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

此代码不打印(0) index 为什么?有人可以帮我解决这个错误吗

【问题讨论】:

    标签: java string recursion netbeans reverse


    【解决方案1】:

    这应该可行:

    public static String reverse(String s) {
        int idx = s.indexOf(" ");
        if (idx < 0) {
            // no space char found, thus, s is just a single word, so return just s itself
            return s;
        } else {
            // return at first the recursively reversed rest, followed by a space char and the first extracted word
            return reverse(s.substring(idx + 1)) + " " + s.substring(0, idx);
        }
    }
    
    public static void main(String[] args) {
        System.out.println(reverse("Cat Is Running"));
    }
    

    【讨论】:

      【解决方案2】:

      此解决方案可能会有所帮助。 cmets 对代码解释得很清楚。

      public static String reverse_recursion(String str) {
          String[] arry = str.split(" ", 2); //Split into a maximum of 2 Strings
      
          if (arry.length > 1) { //If there is more than 1 word in arry
              //Return the reverse of the rest of the str (arry[1])           
              //and concatenate together with the first word (arry[0])
              return reverse_recursion(arry[1]) + " " + arry[0];
          }
      
          return arry[0]; //If less than or equal to 1 word, just return that word
      }
      

      【讨论】:

      • 非常感谢您的帮助
      • @user318974 没问题。如果此答案对您有所帮助,请将其标记为已接受的答案:)
      • @MuhammadUsama 现在可以正常工作了。测试用例:Hello World From Here 变为 Here From World Hello
      【解决方案3】:

      您下次发送的是数组的最后一个元素,而不是没有先前打印的字符串的字符串。

      用这个替换你的return语句应该可以工作。

      return reverse_recursion(n==0?null:str.substring(0,(str.length()-Arry[n].length())-1));
      

      【讨论】:

        猜你喜欢
        • 2014-07-10
        • 1970-01-01
        • 2012-04-01
        • 2020-02-22
        • 2014-06-07
        • 2014-02-27
        • 2017-07-20
        • 2018-04-05
        相关资源
        最近更新 更多