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.
Subscribe to see which companies asked this question.
Show Similar Problems
Have you met this question in a real interview?
public class Solution {
public String reverseWords(String s) {
StringBuilder re = new StringBuilder();
StringBuilder temp = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c != ' ') {
temp.insert(0, c);
} else {
re.append(temp).append(c);
temp = new StringBuilder();
}
}
return re.append(temp).toString();
}
}