Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
time: O(n), space: O(1)
class Solution { public String reverseWords(String s) { String[] strs = s.split(" "); StringBuilder sb = new StringBuilder(); for(String str : strs) { StringBuilder tmp = new StringBuilder(str); sb.append(tmp.reverse().append(" ")); } return sb.toString().trim(); } }
faster, time: O(n), space: O(1)
class Solution { public String reverseWords(String s) { char[] str = s.toCharArray(); int i = 0, j = 0; while(j < str.length) { if(str[j] == ' ') { reverse(str, i, j - 1); j++; i = j; } else { j++; } } reverse(str, i, j - 1); // last word return new String(str); } private void reverse(char[] c, int i, int j) { while(i < j) { char tmp = c[i]; c[i] = c[j]; c[j] = tmp; i++; j--; } } }