Very Easy Java Code(No String Builder)


  • 0
    D
    public String reverseWords(String s) {
        char[] all = s.toCharArray();
        int begin=0;
        for(int i=0;i<s.length();i++){
            if(all[i] == ' '){
                reverse(all,begin,i-1);
                begin = i+1;
            }
        }
        reverse(all,begin,s.length()-1);
        return new String(all);
    }
    
    public void reverse(char[] all, int start, int end){
        while(start < end){
            char temp = all[start];
            all[start] = all[end];
            all[end] = temp;
            start++;
            end--;
        }
    }

Log in to reply
 

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