自己做出来了,但是代码冗长
看了剑指Offer的答案代码,跟我的思路差不多,但是因为书上没说多个空格按一个空格处理,所以他的实现不是很可取。
要注意的
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;
}