题目描述
- 用栈来做挺简单的,也可以用双指针。
思路 & 代码
- 既然是反向,那么从后往前,用双指针截取出字符串即可。
class Solution {public String reverseWords(String s) {StringBuilder ans = new StringBuilder();s = s.trim();int left = s.length() - 1, right = left;while(left >= 0){while(left >= 0 && s.charAt(left) != ' '){left--;}ans.append(s.substring(left + 1, right + 1) + " ");while(left >= 0 && s.charAt(left) == ' '){left--;}right = left;}return ans.toString().trim();}
}
二刷
class Solution {public String reverseWords(String s) {s = s.trim();StringBuilder sb = new StringBuilder();int left = s.length() - 1;while(left >= 0) {int right = left;while(left >= 0 && s.charAt(left) != ' ') {left--;}sb.append(" ").append(s.substring(left + 1, right + 1));while(left >= 0 && s.charAt(left) == ' ') {left--;}}return sb.toString().trim();}
}