Reverse words in a String I
Question:
Given an input string s, reverse the string word by word.
For example, given s = “the sky is blue”, return “blue is sky the”.
*Difficulty: Medium, Frequency: High
https://leetcode.com/problems/reverse-words-in-a-string/
My Solution
public String reverseWords(String s) {
s = s.trim();
if(s.isEmpty() || !s.contains(" ")) return s;
String[] strAry = s.split(" ");
StringBuffer bf = new StringBuffer();
for(int i = strAry.length-1; i >=0; i--){
if(!strAry[i].trim().isEmpty()){
bf.append(strAry[i]);
if(i != 0) bf.append(" ");//don't forget to add back space
}
}
return bf.toString();
}
Standard Solution
O(n) runtime, O(n) space
public String reverseWords(String s) {
StringBuilder reversed = new StringBuilder();
int j = s.length();
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
j = i;
} else if (i == 0 || s.charAt(i - 1) == ' ') {
if (reversed.length() != 0) {
reversed.append(' ');
}
reversed.append(s.substring(i, j));
}
}
return reversed.toString();
}
Reverse Words in a String II - no extra space allocation
Question
Similar to Question in I, but with the following constraints:
“The input string does not contain leading or trailing spaces and the words are always separated by a single space.”
Could you do it in-place without allocating extra space?
*Difficulty: Medium, Frequency: N/A
My Solution
Thoughts: reverse the string first, and reverse each word
e.g. “the sky is blue” -> “eulb si yks eht” -> “blue is sky the”
public char[] reverseWord2(char[] s){
int j = 0;
s = swapMirrorStr(s, 0, s.length);
int start = 0, end =0;
for(int i = 0; i < s.length; i++){
if(s[i]==' ') {
end = i;
s = swapMirrorStr(s, start, end);
start = i+1;
}
if(i == s.length-1) s = swapMirrorStr(s, start, s.length);
}
return s;
}
private char[] swapMirrorStr(char[] s, int start, int end){
for(int i = 0; i < (end-start)/2; i++){
char tmp = s[start+i];
s[start+i] = s[end-1-i];
s[end-1-i] = tmp;
}
return s;
}
Standard Solution
public void reverseWords(char[] s) {
reverse(s, 0, s.length);
for (int i = 0, j = 0; j <= s.length; j++) {
if (j == s.length || s[j] == ' ') {
reverse(s, i, j);
i = j + 1;
}
}
}
private void reverse(char[] s, int begin, int end) {
for (int i = 0; i < (end - begin) / 2; i++) {
char temp = s[begin + i];
s[begin + i] = s[end - i - 1];
s[end - i - 1] = temp;
}
}