题解 | #翻转单词序列#
翻转单词序列
http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
遍历字符串,把每个空格前的字符串加入数组,反向遍历数组,拼接得到结果字符串
import java.util.ArrayList; public class Solution { public String ReverseSentence(String str) { String res=""; //start记录当前单词头,end记录当前单词尾 int start=0,end=0; ArrayList res1=new ArrayList(); while (true){ //如果尾巴超出字符串,则把最后一个单词收入数组,停止 if(end>str.length()-1){ res1.add(str.substring(start,end)); break; } if(str.charAt(end)!=' '){ end++; } //把当前单词加入数组,并更新单词头 else { res1.add(str.substring(start,end)); end++; start=end; } } for (int i = res1.size()-1; i>=0 ; i--) { res+=res1.get(i); if(i-1>=0){ res+=" "; } } return res; } }