The following problem is from LeetCode:
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"
The following code is working correctly, but its runtime is 8 ms, which is only faster than 42.44% of Java online submissions. How to make the following code faster?
class Solution {
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
int length = s.length();
int start = 0;
int end = 0;
while(start < length){
while( (end < length) && (s.charAt(end) != ' ')){
end++;
}
doReverse(s, start, end -1, sb);
start = ++end;
}
return sb.toString();
}
private void doReverse(String s, int start, int end, StringBuilder sb){
if(start >0)
sb.append(" ");
while(end >= start){
sb.append(s.charAt(end));
end--;
}
}
}