Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "Mr Ding"
Output: "rM gniD"
Constraints:
- 1 <= s.length <= 5 * 104
- s contains printable ASCII characters.
- s does not contain any leading or trailing spaces.
- There is at least one word in s.
- All the words in s are separated by a single space.
My Solution
We can first use the Java split method to split the String into an array of strings delimited by a space. We then initialize an empty StringBuilder. We iterate through the array of Strings, create a StringBuilder with the current string, reverse it and then append the reversed string along with a space to our output StringBuilder. Finally there will be one extra space at the end, so we just delete the last character of the StringBuilder. We return that underlying string.
Time complexity is O(n) due to the Java split method and iterating through all the strings and reversing them. Space complexity is also O(n) due to the extra space required for the array of strings and the StringBuilder we initialize for each string in the array.
class Solution {
public String reverseWords(String s) {
String[] strs = s.split(" ");
StringBuilder sb = new StringBuilder();
for (String str : strs) {
StringBuilder str_sb = new StringBuilder(str);
sb.append(str_sb.reverse());
sb.append(" ");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
}