[JAVA] iterate and reverse when we discover space / T : O(N), S : O(N)


  • 0
    J
    public class Solution {
        public String reverseWords(String s) {
            int i = 0;
            int j = 0;
            char[] chs = s.toCharArray();
            while(j < chs.length){
                if(chs[j] ==' '){
                    swapAll(chs, i, j-1);
                    while(chs[j] == ' '){
                        j++;
                    }
                    i = j;
                }
                else{
                    j++;
                }
            }      
            
            if(chs.length != 0 && chs[chs.length-1] != ' '){
                swapAll(chs, i, j-1);
            }
            
            
            return String.valueOf(chs);
        }
        
        public void swapAll(char[] chs, int i, int j){
            while(i < j){
                char temp = chs[i];
                chs[i] = chs[j];
                chs[j] = temp;
                
                i++;
                j--;
            }
        }
    }
    

Log in to reply
 

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