Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.
X

LeetCode: Reverse Words in a String (2ms)


public class Solution {
    public String reverseWords(String s) {
        s = s.trim();

        List 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 split(String string) {
        int old_posn=0,posn=0;

        List str = new ArrayList();

        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;
    }
}


comments powered by Disqus