Java 中使用递归方法进行字符串反转不起作用,但为什么呢?

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

我编写该程序作为算法练习任务。 该方法应该获取一个字符串并将其转换为字符数组。 然后将最后一个字符与第一个字符交换,依此类推。 但我很困惑,即使我可能知道这个错误,但我不知道如何修复它。

这是代码:

package Rekursion;

public class StringReversal {

    char[] chars;
    int i = 0;
    int j;

    public String reversString(String text) {

        chars = text.toCharArray();
        j = chars.length-1;//Here i think is the mistake where j gets reset to array length and doesnt iterate properly but i need the length inside the method because of the parsed String


        if (i > j) {
            return String.valueOf(chars);
        }

        else {

            char temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;

            i++;
            j--;

            return reversString(String.valueOf(chars));
        }
    }

public static void main(String[] args) {
      StringReversal sr = new StringReversal();
        System.out.print(sr.reversString("gras"));
    }
}

这是控制台输出:sgra

但预期输出是:sarg

我尝试过适应这种情况,但情况应该很好。我什至不知道如何修复我评论的错误

java algorithm recursion
1个回答
0
投票

您确实正确地识别了问题,简单的解决方法是提供

i
j
作为方法的参数,并在调用
0
方法时传递起始值(即
s.length()-1
reverseString
)在
main
方法中。 您还可以通过不每次都将
String
转换为字符数组来改进程序。您可以将字符数组作为参数传递一次,然后在返回时将其转换回 String

public class StringReversal {

    public String reversString(char[] chars, int i, int j) { 

        if (i > j) {
            return new String(chars);
        }

        else {

            char temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;

            i++;
            j--;

            return reversString(chars,i,j);
        }
    }

    public static void main(String[] args) {
        StringReversal sr = new StringReversal;
        String s = "gras";
        System.out.print(m.reversString(sr.toCharArray(), 0, s.length()-1));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.