题解 | #翻转单词顺序列#
翻转单词顺序列
http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
public String ReverseSentence(String str) {
//可以用一个stringBuilder试一下?
StringBuilder stringBuilder=new StringBuilder("");//stringBuilder来追加
char[] chars = str.toCharArray();//转字符
int i=chars.length-1;//从后往前
while(i>=0)
{
ArrayList arrayList=new ArrayList();
while(chars[i]!=' '&&i>=0)//遇到空格就停止
{
arrayList.add(chars[i]);//遇到空格前存一下这部分字符
if(i>0)
i--;
else break;
}
for(int k=arrayList.size()-1;k>=0;k--)
stringBuilder.append(arrayList.get(k));//每一个单词里面反过来
if(stringBuilder.length()!=chars.length) stringBuilder.append(" ");
if(i>0) i--;
else break;
}
return stringBuilder.toString();
}