my java solution use stack ,not use the String.split() method


  • 0
    L
     public String reverseWords(String s) {
         Stack<String> stack = new Stack<String>();
         int start = -1,end = 0;
         char c;
         for(int i = 0; i < s.length(); i++){
             c = s.charAt(i);
             if(c == ' ') {
                 if(start == -1) {
                     continue;
                 }else{
                     stack.push(s.substring(start,end + 1));
                     start = -1;
                 }
             }
             else{
                 if(start == -1){
                     start = i;
                 }
                 end = i;
             }
         }
         if(start >= 0){
             stack.push(s.substring(start,end + 1));
         }
         StringBuffer buffer = new StringBuffer("");
         int size = stack.size();
         for(int i = 0; i < size ; i++){
             buffer.append(stack.pop());
             if( i < size - 1){
                 buffer.append(" ");
             }
         }
         return buffer.toString();
    }

Log in to reply
 

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