3ms Java (84.54%)


  • 0
    L
    public String reverseWords(String s) {
        char[] chs = s.toCharArray();
        int left = 0, right = chs.length - 1;
        while(left < chs.length && chs[left] == ' ') left++;
        while(right >= 0 && chs[right] == ' ') right--;
        if(left > right) return "";
        int i = left, j = left, next = left;
        while(i <= right && j <= right){
            while(i <= right && chs[i] == ' ') i++;
            j = i;
            while(j <= right && chs[j] != ' ') j++;
            reverse(chs, i, j - 1);
            if(next < i){
                for(int w = i; w < j; w++){
                    chs[next++] = chs[w];
                }
                chs[next++] = ' ';
            }else{
                next = j + 1;
            }
            i = j + 1;
        }
        if(next <= right + 1) right = next - 2;
        reverse(chs, left, right);
        return new String(chs, left, right - left + 1);
    }
    
    private void reverse(char[] chs, int left, int right){
        for(int wL = left, wR = right; wL < wR; wL++, wR--){
            char ch = chs[wL];
            chs[wL] = chs[wR];
            chs[wR] = ch;
        }
    }

Log in to reply
 

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