[LC] 151. Reverse Words in a String
Given an input string, reverse the string word by word.
Example 1:
Input: "the sky is blue
" Output: "blue is sky the
"
Example 2:
Input: " hello world! " Output: "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Solution 1:
class Solution { public String reverseWords(String s) { if (s == null || s.length() == 0) { return ""; } char[] charArr = s.toCharArray(); swap(charArr, 0, s.length() - 1); int i = 0, start = 0; while (i < s.length()) { if (i == 0 || charArr[i - 1] == ' ') { start = i; } if (i == charArr.length - 1 || charArr[i + 1] == ' ') { swap(charArr, start, i); } i += 1; } // need to trim space inside int slow = 0; for (int j = 0; j < charArr.length; j++) { if (charArr[j] == ' ' && (j == 0 || charArr[j - 1] == ' ')) { continue; } charArr[slow++] = charArr[j]; } return new String(charArr, 0, slow).trim(); } private void swap(char[] charArr, int i, int j) { while (i < j) { char tmp = charArr[i]; charArr[i] = charArr[j]; charArr[j] = tmp; i += 1; j -= 1; } } }
Solution 2:
class Solution { public String reverseWords(String s) { if (s == null || s.length() == 0) { return ""; } String[] strArr = s.split("\\s+"); StringBuilder sb = new StringBuilder(); for (int i = strArr.length - 1; i >= 0; i--) { sb.append(strArr[i] + " "); } return sb.toString().trim(); } }