Neat Java Solution creating our own split and reverse function.


  • 0
    public class Solution {
        public String reverseWords(String s) {
            String words[] = split(s);
            String res = "";
            for (String word: words)
                res += reverse(word) + " ";
            return res.trim();
        }
        public String[] split(String s) {
            ArrayList < String > words = new ArrayList < > ();
            String word = "";
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == ' ') {
                    words.add(word);
                    word = "";
                } else
                    word += s.charAt(i);
            }
            words.add(word);
            return words.toArray(new String[words.size()]);
        }
        public String reverse(String s) {
            String res = "";
            for (int i = 0; i < s.length(); i++)
                res = s.charAt(i) + res;
            return res;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.