Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
思路:从后向前走,然后遍历到第i个的时候,判断第i个和第i-1个的关系,从而进行不同的操作,最后一个case 4的代码是LeetCode可以跑过的代码。
case 1: no leading space, no tailing space, no continuous inner space
public String reverseWords(String s) {
//special case
if (s.length() == 1) return "";
//general case
StringBuilder sb = new StringBuilder();
int end = s.length();
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
sb.append(s.substring(i + 1, end));
sb.append(" ");
end = i;
}
}
sb.append(s.substring(0, end));
return sb.toString();
}
case2: no leading space, no tailing space, has continuous inner space
public String reverseWords(String s) {
//special case
if (s.length() == 0) return "";
if (s.length() == 1) {
if (s.equals(" ")) return "";
else return s;
}
//general case
StringBuilder sb = new StringBuilder();
int end = s.length();
for (int i = s.length() - 2; i >= 0; i--) {
if (s.charAt(i) == ' ' && s.charAt(i + 1) != ' ') {
sb.append(s.substring(i + 1, end));
if (i != 0) sb.append(" ");
end = i;
}
if (s.charAt(i) == ' ' && s.charAt(i + 1) == ' ') {
end = i;
}
}
if (end != s.length()) sb.append(s.substring(0, end));
return sb.toString();
}
case3: has leading space, no tailing space, has continuous inner space
//special case
if (s.length() == 0) return "";
if (s.length() == 1) {
if (s.equals(" ")) return "";
else return s;
}
//general case
StringBuilder sb = new StringBuilder();
int end = s.length();
for (int i = s.length() - 2; i >= 0; i--) {
if (s.charAt(i) == ' ' && s.charAt(i + 1) != ' ') {
sb.append(s.substring(i + 1, end));
if (i != 0) sb.append(" ");
end = i;
}
if (s.charAt(i) == ' ' && s.charAt(i + 1) == ' ') {
end = i;
}
}
if (end != s.length()) sb.append(s.substring(0, end));
String res = sb.toString();
if (res.length() != 0 && res.charAt(res.length() - 1) == ' ') res = res.substring(0, res.length() - 1);
return sb.toString();
case4: has leading space, has tailing space, has continuous inner space
//special case
if (s.length() == 0) return "";
if (s.length() == 1) {
if (s.equals(" ")) return "";
else return s;
}
//general case
StringBuilder sb = new StringBuilder();
int end = s.length();
for (int i = s.length() - 2; i >= 0; i--) {
if (s.charAt(i) == ' ' && s.charAt(i + 1) != ' ') {
sb.append(s.substring(i + 1, end));
if (i != 0) sb.append(" ");
end = i;
}
if (s.charAt(i) == ' ' && s.charAt(i + 1) == ' ') {
end = i;
}
if (s.charAt(i) != ' ' && s.charAt(i + 1) == ' ') {
end = i + 1;
}
}
sb.append(s.substring(0, end));
String res = sb.toString();
if (res.length() != 0 && res.charAt(res.length() - 1) == ' ') res = res.substring(0, res.length() - 1);
return res;