Java solution 6ms


  • 0
    S
    public class Solution {
        public void reverseWords(char[] s) {
            boolean haveSpaces = false;
            for(int i = 0 ; i < s.length ; i++){
                if(s[i] == ' '){
                    haveSpaces = true;
                }
            }
            if(!haveSpaces){
                return;
            }
            reverse(s, 0, s.length-1);
            int start = 0;
            for(int i = 0 ; i < s.length ; i++){
                if(s[i] == ' '){
                    reverse(s, start, i-1 );
                    start = i+1;
                }
            }
            reverse(s , start, s.length-1);
        }
        private void reverse(char[] s, int start, int end){
            while(start < end){
                char temp = s[start];
                s[start] = s[end];
                s[end] = temp;
                start++;
                end--;
            }
        }
    }
    

Log in to reply
 

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