Java using char[]


  • 0
    V
    public String reverseWords(String s) {
            
            if (s.equals(""))
                return s;
        
            char[] chars = s.toCharArray();
            
            int i = 0;
            for(int j=0; j < chars.length;j++){
                if(chars[j] == ' ' || j == chars.length-1){
                    int t1 = i;
                    int t2 = (j != chars.length-1) ? j-1 : j;
                    while(t1 < t2){
                        char ch = chars[t1];
                        chars[t1] = chars[t2];
                        chars[t2] = ch;
                        t1++; t2--;            
                    }
                    i = j + 1;
                }
            }
            return new String(chars);
        }
    

Log in to reply
 

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