Java 8ms (in-place)


  • 2
    L
    public class Solution {
        public String reverseWords(String s) {
            char[] str = reverseWords(s.toCharArray());
            return removeSpaces(str);
        }
        
        private char[] reverseWords(char[] str) {
            reverse(str, 0, str.length - 1);
            
            int start = 0;
            int end = 0;
            for(int i = 0; i < str.length; i++) {
                if(str[i] == ' ') {
                    if(end > start) reverse(str, start, end);
                    start = end = i + 1;
                } else {
                    end = i;
                }
            }
            
            if(end > start) reverse(str, start, end);
            
            return str;
        }
        
        private void reverse(char[] str, int i, int j) {
            while(i < j) {
                char tmp = str[i];
                str[i] = str[j];
                str[j] = tmp;
                i++;
                j--;
            }
        }
    
        private String removeSpaces(char[] str) {
            int ptr = 0;
            int len = 0;
            boolean skip = true;
            
            for(int i = 0; i < str.length; i++) {
                if(skip && (str[i] == ' ')) continue;
                
                str[ptr++] = str[i];
                skip = (str[i] == ' ');
                len++;
            }
            
            if((len > 0) && (str[len - 1] == ' ')) len--;
    
            return (len == 0) ? "" : new String(str, 0, len);
        }
    }

  • 0
    C

    What is the logic behind removeSpaces
    private String removeSpaces(char[] str) {
    int ptr = 0;
    int len = 0;
    boolean skip = true;

        for(int i = 0; i < str.length; i++) {
            if(skip && (str[i] == ' ')) continue;
    
            str[ptr++] = str[i];
            skip = (str[i] == ' ');
            len++;
        }
    
        if((len > 0) && (str[len - 1] == ' ')) len--;
    
        return (len == 0) ? "" : new String(str, 0, len);
    }

Log in to reply
 

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