151. Reverse Words in a String
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public String reverseWords(String s) {
int i = s.length()-1;
StringBuilder result = new StringBuilder();
while(i >= 0) {
while(i >= 0 && s.charAt(i) == ' ') {
i--;
}
String tmp = "";
while(i >= 0 && s.charAt(i) != ' ') {
tmp = s.charAt(i) + tmp;
i--;
}
if(tmp.length() > 0) {
result.append(" ").append(tmp);
}
}
if(result.length() == 0) {
return result.toString();
}
return result.substring(1);
}
}/**
* Time complexity :
* Space complexity :
*/
class Solution {
public String reverseWords(String s) {
StringBuilder result = new StringBuilder();
String[] words = s.split(" ");
for(int i = words.length-1; i >= 0; i--) {
if(words[i].isEmpty()) continue;
result.append(words[i]).append(" ");
}
return result.toString().trim();
}
}