Clarifications
What constitutes a word?
- A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
- Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
- Reduce them to a single space in the reversed string.
Thinking process I
Split the input string, skip all the substrings whose length is 0 (white spaces)
Append the substring reversely to the string builder
Mistakes
Append to the string builder, instead of insert at the front
public class Solution {
public String reverseWords(String s) {
String[] strs = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = strs.length - 1; i >= 0; --i) {
if (strs[i].length() == 0) continue;
sb.append(strs[i]);
sb.append(" ");
}
return sb.toString().trim();
}
}
Thinking process II
Don't need to split the string, use two pointers to remember the start and end position of a word, and append it to string builder
public class Solution {
public String reverseWords(String s) {
StringBuilder result = new StringBuilder();
int endOfWord = s.length();
for (int i = s.length() - 1; i >= 0; --i) {
if (s.charAt(i) == ' ') {
endOfWord = i;
} else if (i == 0 || s.charAt(i - 1) == ' ') {
result.append(s.substring(i, endOfWord));
result.append(' ');
}
}
return result.toString().trim();
}
}
or
public class Solution {
public String reverseWords(String s) {
StringBuilder result = new StringBuilder();
int endOfWord = s.length();
for (int i = s.length() - 1; i >= 0; --i) {
if (s.charAt(i) == ' ') {
endOfWord = i;
} else if (i == 0 || s.charAt(i - 1) == ' ') {
if (result.length() != 0) {
result.append(' ');
}
result.append(s.substring(i, endOfWord));
}
}
return result.toString();
}
}
Follow ups - LC 186 Reverse Words in a String II
public class Solution {
public void reverseWords(char[] s) {
reverse(s, 0, s.length - 1);
int startOfWord = 0;
for (int i = 0; i <= s.length; i++) {
if (i == s.length || s[i] == ' ') {
reverse(s, startOfWord, i - 1);
startOfWord = i + 1;
}
}
}
private void reverse(char[] s, int start, int end) {
while (start < end) {
char tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}
}
}