對於解決方案,我引用了Whats the best way to recursively reverse a string in Java?,但是我的解決方案和我不明白的正確解決方案之間存在細微的差異。用Java以遞歸方式反轉字符串
我想通過命令行反轉參數中的字符串。這是我的遞歸方法來反轉字符串(幾乎相同)。但是,我遇到了StackOverflowException。我想知道這是爲什麼?是因爲我的方法是靜態方法,而他們的方法不是?
public static String reverse(String word) {
if (word.length() == 1) {
return word;
} else {
return reverse(word.substring(1) + word.charAt(0));
}
}
將word.charAt(0)從括號中取出。 – matt