Straight forward Java solution using stack with explanation


  • 0
    V

    public class Solution {

    public String reverseWords(String s) {
    
       //if s is null 
       if(s.length() == 0){
    		return "";
    	}
    	//if s contains no word,just return ""
    	int whiteSpace = 0;
    	for(int i = 0; i < s.length(); i++){
    	    if(s.charAt(i) == ' '){
    	        whiteSpace++;
    	    }
    	}
    	if(whiteSpace == s.length()){
    	    return "";
    	}
    	
    	
    	Stack<String> stack = new Stack<String>();
    	int wordBegins = 0;
    	for(int i = 0; i < s.length(); i++){
    	    if(s.charAt(i) == ' '){
    	        //if first character is " ", add nothing to stack,else add words
    	        //from left to right one by one
    	        if(i != wordBegins){
    	    	  stack.push(s.substring(wordBegins, i));
    	        }
    	    	wordBegins = i + 1;
    	    }
    	}
    	//add the last word
    	if(wordBegins != s.length()){
    	      stack.push(s.substring(wordBegins, s.length()));
    	}
    	//if s is one word, just return s.
    	if(wordBegins == 0){
    	    return s;
    	}
    	
    	StringBuilder str = new StringBuilder();
    	while(!stack.isEmpty()){
    		str.append(stack.pop() + " ");
    	}
        str.deleteCharAt(str.length()-1);
       return str.toString();
    }
    

    }


Log in to reply
 

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