Java 12ms solution, easy to understand


  • 0
    Y

    public class Solution {

    public String reverseWords(String s) {
        if (s == null) return s;
        char[] ch = s.toCharArray();
        int count = 0;
        for (int i = 0; i < ch.length; i++){
            if (ch[i] == ' '){
                reverse(ch, i - count, i - 1);
                count = 0;
            } else if (i == ch.length - 1){ //deal with last word
                reverse(ch, i - count, i);
            } else {
                count++;
            }
        }
        return new String(ch);
    }
    
    private void reverse(char[] ch,int i,int j){
        while(i < j){
            char tmp = ch[j];
            ch[j] = ch[i];
            ch[i] = tmp;
            i++;
            j--;
        }
    } 
    

    }


Log in to reply
 

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