Demo entry 6714508

Leetcode186

   

Submitted by anonymous on Feb 13, 2018 at 17:41
Language: Java. Code size: 756 Bytes.

class Solution {
    public void reverseWords(char[] str) {
        if(str == null || str.length == 0)
            return;
        reverse(0,str.length - 1,str);
        
        int head = 0;
        int tail = 0;
        while(tail < str.length){
            if(str[tail] == ' '){
                reverse(head,tail - 1,str);
                head = tail + 1;
            }
            tail ++;
        }
        
        if(head < str.length)
            reverse(head,tail - 1,str);
    }
    
    public void reverse(int head,int end,char[] ch){
        while(head < end){
            char temp = ch[head];
            ch[head] = ch[end];
            ch[end] = temp;
            head ++;
            end --;
        }
    }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).