Skip to content

Instantly share code, notes, and snippets.

@b27lu
Created March 10, 2014 16:35
Show Gist options
  • Save b27lu/9468573 to your computer and use it in GitHub Desktop.
Save b27lu/9468573 to your computer and use it in GitHub Desktop.
Reverse Words in a String at LeetCode
public class Solution {
public String reverseWords(String s) {
if(s == null)
return s;
//trim leading and trailing spaces
String trimmed = s.trim();
//split string using space(s) as delimiter
String[] splitted = trimmed.split("\\s+");
StringBuilder sb = new StringBuilder();
for(int i = splitted.length - 1;i>=0;i--){
sb.append(splitted[i]);
if(i != 0)
sb.append(" ");
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment