Use toCharArray() function, is this in place solution?


  • 0
    G

    I reverse the whole string and then reverse every word respectively. I use toCharArray() function, anyone tell me is this solution in place? Thanks!

    public class Solution {
    public String reverseWords(String s) {
        s=s.trim();
        s=s.replaceAll("\\s+"," ");
        s=" "+s;
        char[] S=s.toCharArray();
        reverse(S,0,s.length()-1);
        int l=0;
        for(int i=0;i<S.length;i++){
            if(S[i]==' '){
                reverse(S,l,i-1);
                l=i+1;
            }
        }
        return String.valueOf(S).trim();
    }
    public void reverse(char[] s,int l,int r){
                int a=l;
                int b=r;
                while(a<b){
                    char tmp=s[b];
                    s[b]=s[a];
                    s[a]=tmp;
                    a++;
                    b--;
                }  
            }
    

    }


Log in to reply
 

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