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
@oluwasayo...I love your solution. It was the same thing I wrote that gave me 3ms. Pretty cool.