public class Solution {
public String reverseWords(String s) {
s = s.trim();
List<String> spl = split(s);
StringBuilder sb = new StringBuilder();
for(int i = spl.size() - 1; i >= 0; i--) {
sb.append(spl.get(i));
sb.append(" ");
}
if ( sb.length() > 0 ) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
public static List<String> split(String string) {
int old_posn=0,posn=0;
List<String> str = new ArrayList<String>();
while (posn >= 0)
{
posn = string.indexOf(' ',old_posn);
String next_word = (posn>0) ?
string.substring(old_posn,posn):
string.substring(old_posn);
if (!next_word.isEmpty()) {
str.add(next_word);
}
old_posn = posn + 1;
}
return str;
}
}
Last active
December 6, 2016 15:56
-
-
Save akinyeleolubodun/76b6927f815820565886642244d7e609 to your computer and use it in GitHub Desktop.
Reverse Words in a String
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice work!
This is the first thing that occurred to me when I saw the problem (I'm lazy). 3 milliseconds on their clock.