问题是在 java 中使用递归按字母顺序对字符串的给定字母进行排序,例如:
input: "hello"
output: ehllo
我试过这段代码:
public class MinSort {
public static void main(String[] args) {
System.out.println(sort("hello"));
}
static String temp="";
static String answer ="";
public static String sort(String s)
{
temp = s.substring(0, 1);
if(s.length()<=1||s==null)
{
return s;
}
else
{
if(temp.compareTo(s.substring(1, 2))>1)
{
answer+=s.substring(0, 1);
}
else
{
answer += temp;
temp = s.substring(1, 2);
}
sort(s.substring(0, s.length()-1));
return answer;
}
}
}
最佳答案
您没有找到第一个字符(按升序)。你应该遍历整个字符串,就像在这个递归 selection sort 中一样(添加了 printf
以可视化迭代):
String ssort(String s) {
if (s.length() < 2) {
return s;
}
int pos = 0;
char min = s.charAt(0);
for(int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (c < min) {
min = c;
pos = i;
}
}
System.out.printf("%c | %s\n", min, s.substring(0, pos) + s.substring(pos + 1));
return min + ssort(s.substring(0, pos) + s.substring(pos + 1));
}
因此 ssort("hello")
产生:
e | hllo
h | llo
l | lo
l | o
ehllo
和ssort("uioea")
产生:
a | uioe
e | uio
i | uo
o | u
aeiou
关于java - 如何在 java 中使用递归对单词 "hello"进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29202762/