https://oj.leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",return "blue is sky the
". public class Solution { public static String reverseWords(String s) { String[] strs = s.split(" "); String str = ""; for (int i = strs.length; i > 0; i--) { if (!strs[i - 1].trim().equals("")) { str += strs[i - 1].trim() + " "; } } return str.trim(); }}
解题思路:
首先trim s,去除开始就有的首尾空格,然后用空格将其split为数组。再倒序,最后trim首尾的空格。
其他思路的解法较多:
例如先倒置整个s,然后从头开始倒置每个单词(遇到空格),再处理头尾的空格和中间的空格。
也可以使用stack的方法,推进去,再取出来。
update 2015/05/28:
二刷,更新一个one pass的解法。从后往前遍历s,记录每个word的左右坐标,然后将其append在结果的后面。
注意,遍历到s的开头,仍然要把第一个word塞进结果。
public class Solution { public String reverseWords(String s) { if(s == null || s.length() == 0) { return s; } StringBuffer res = new StringBuffer(); int start = -1, end = -1; for(int i = s.length() - 1; i >= 0; i--) { if(s.charAt(i) == ' ') { if(start != -1 && start <= end) { res.append(s.substring(start, end + 1)); res.append(" "); } start = -1; end = -1; } else { if(start == -1) { start = i; end = i; } else { start = i; } } } if(start != -1 && start <= end) { res.append(s.substring(start, end + 1)); } return res.toString().trim(); }}
//2018/06/21
public class Solution { public String reverseWords(String s) { int head = 0, tail = 0; String result = ""; while (head < s.length() && tail < s.length()) { if (s.charAt(head) == ' ') { head++; } else { if(tail < head) { tail = head; } if (s.charAt(tail) != ' ') { tail++; } else { result = s.substring(head, tail) + " " + result; head = tail; } } } if (head < tail) { result = s.substring(head, tail) + " " + result; } return result.trim(); }}