Help improve my O(1) space complexity solution


  • 0
    Z
    public static void reverseStr(char[] A, int start, int end){
        char tmp;
        while(start < end){
            tmp = A[start];
            A[start] = A[end];
            A[end] = tmp;
    
            start++;
            end--;
        }
    }
    
    //a O(1) space way
    public static String revertWords(String s) {
        s.trim();
        char[] A = s.toCharArray();
        if(A == null || A.length == 0)return s;
    
        //reverse all firstly
        reverseStr(A, 0 , A.length-1);
        //reverse every single word
        int j = 0;
        for (int i = 0; i < A.length; i++) {
            if(A[i] == ' '){
                reverseStr(A, j, i-1);
                j = i+1;
            }
            if(i == A.length -1){
                reverseStr(A, j, i);
            }
        }
        //is there any better solution can remove the duplicated whitespaces?
        return new String(A).trim().replaceAll(" +" , " ");
    }
    

    The only problem is that i am using regular expression which was not so efficient i think!
    any better solution that can remove duplicated spaces.


Log in to reply
 

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