Java two methods, 3 line using built-in and char[] array


  • 0

    Java Built-in:

        public String reverseWords(String s) {
            String[] strs = new StringBuilder(s).reverse().toString().split("\\s");
            Collections.reverse(Arrays.asList(strs));
            return String.join(" ", strs);
        }
    

    Use char[] array (much faster):

    public String reverseWords(String s) {
            char[] chs = s.toCharArray();
            for (int i = 0; i < chs.length; i++) {
                int j = i;
                while (j+1 < chs.length && chs[j+1] != ' ') j++;
                int lo = i, hi = j;
                while (lo < hi) {
                    char tmp = chs[lo];
                    chs[lo++] = chs[hi];
                    chs[hi--] = tmp;
                }
                i = j+1;
            }
            return new String(chs);
        }
    

Log in to reply
 

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