- 从字符串尾开始,碰到空格就加入新字符串
public class Solution { public String ReverseSentence(String str) { StringBuilder res = new StringBuilder(); int start = str.length(), end = str.length(); while(--start >= 0) { // 每碰到空格就组合 if(str.charAt(start) == ' ') { res.append(str.substring(start + 1, end)); res.append(' '); end = start; } } res.append(str.substring(start + 1, end)); return res.toString(); } }