自分で作ったのですが、コードが冗長です
Jianzhi Offerの回答コードを読んだ後、それは私の考えに似ていますが、本は複数のスペースが1つのスペースとして扱われるとは述べていないため、彼の実装はあまり望ましくありません。
注意すべき点
char[] s_c_old = s.toCharArray();
StringBuilder res = new StringBuilder();
res.append(s_c[count_in]);
String res_s = res.toString();
私のコード
public String reverseWords(String s) {
char[] s_c_old = s.toCharArray();
int new_length = s_c_old.length;
int count = 0;
int start_index = count;
for(;start_index<s_c_old.length;start_index++){
if(s_c_old[start_index] == ' '){
new_length--;
}else{
break;
}
}
int last_index = s_c_old.length - 1;
for(;last_index>=0;last_index--){
if(s_c_old[last_index] == ' '){
new_length--;
}else{
break;
}
}
for(count = start_index;count<=last_index;count++){
if(count > 0){
if(s_c_old[count] == ' '&&s_c_old[count-1] == ' '){
new_length--;
}
}
}
if(new_length<=0){
return "";
}
char[] s_c = new char[new_length];
int s_c_count = 0;
for(count = start_index ;count<=last_index;count++){
if(count > start_index){
if(s_c_old[count]!=' '&&s_c_old[count-1]==' '){
s_c[s_c_count++] = ' ';
s_c[s_c_count++] = s_c_old[count];
}else if(s_c_old[count]!=' '&&s_c_old[count-1]!=' '){
s_c[s_c_count++] = s_c_old[count];
}
}else{
if(s_c_old[count]!=' '){
s_c[s_c_count++] = s_c_old[count];
}
}
}
StringBuilder res = new StringBuilder();
for(int count_out = s_c.length - 1;count_out >=0;count_out--){
if(s_c[count_out]==' '){
for(int count_in = count_out + 1;count_in < s_c.length&&s_c[count_in]!=' ';count_in++){
res.append(s_c[count_in]);
}
res.append(' ');
}
}
for(int count_in = 0;count_in < s_c.length&&s_c[count_in]!=' ';count_in++){
res.append(s_c[count_in]);
}
String res_s = res.toString();
return res_s;
}