Created
March 10, 2014 16:35
-
-
Save b27lu/9468573 to your computer and use it in GitHub Desktop.
Reverse Words in a String at LeetCode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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