Share My Java solution


  • 0
    P

    Simple idea:

    1. reverse every word in the string
    2. reverse the whole string

    be careful with the whitespace and the last word in the string

        //"the sky is blue"
    public void reverseWords(char[] s) {
        if(s == null || s.length == 0) return;
        int start = 0;
        int end = -1;
        int i = start;
        // reverse every word in the string => "eht yks si eulb"
        while(i<s.length){
            if(s[i] == ' ' || i == s.length-1){
                end = s[i] == ' '?i-1:i;
                reverse(s, start, end);
                start = i+1;
            }
            i++;
            
        }
        
        //reverse the whole string => "blud is sky the"
        reverse(s, 0, s.length-1);
    }
    
    private void reverse(char[] s, int start, int end){
        while(start<end){
            char tmp = s[start];
            s[start] = s[end];
            s[end] = tmp;
            start++;
            end--;
        }
    }

Log in to reply
 

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