yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #151 Reverse Words in a String #150

Open yokostan opened 5 years ago

yokostan commented 5 years ago

As a qualified programmer, you should know how to utilize double while loops!

class Solution {
    public String reverseWords(String s) {
        if (s == null) {
            return null;
        }

        char[] a = s.toCharArray();
        int n = a.length;

        reverse(a, 0, n - 1);
        reverseWords(a, n);

        return cleanSpaces(a, n);    
    }

    private void reverse(char[] a, int start, int end) {
        while (start < end) {
            char temp = a[start];
            a[start] = a[end];
            a[end] = temp;
            start++;
            end--;
        }
    }

    private void reverseWords(char[] a, int n) {
        int  i = 0, j = 0;
        while (i < n) {
            while (i < j || i < n && a[i] ==' ') i++;
            while (j < i || j < n && a[j] != ' ') j++;
            reverse(a, i, j - 1);
        }
    }

    private String cleanSpaces(char[] a, int n) {
        int i = 0, j = 0;
        while (j < n) {
            while (j < n && a[j] == ' ') j++;
            while (j < n && a[j] != ' ') a[i++] = a[j++];
            while (j < n && a[j] == ' ') j++;
            if (j < n) a[i++] = ' ';
        }

        return new String(a).substring(0, i);
    }
}