More elegant solution without trim()


  • 0
    G
    public class Solution {
        public String reverseWords(String s) {
            char [] A = s.toCharArray();
            reverse(A, 0, s.length() - 1);
            int pre = -1;
            for (int i = 0; i <= s.length(); i++) {
                if (i == s.length() || A[i] == ' ') {
                    reverse(A, pre + 1, i - 1);
                    pre = i;
                }
            }
            int res = 0;
            boolean firstWord = true;
            for (int i = 0; i < A.length; i++) {
                if (A[i] != ' ') {
                    if (!firstWord && A[i - 1] == ' ') {
                        A[res++] = ' ';
                    }
                    A[res++] = A[i]; 
                    firstWord = false;
                }
            }
            return (new String(A)).substring(0, res);
        }
        
        public void reverse(char [] A, int s, int e) {
            while (s < e) {
                char tmp = A[s];
                A[s] = A[e];
                A[e] = tmp;
                s++;
                e--;
            }
        }
    }
    

Log in to reply
 

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