Using Stack


  • 0
    P

    Hi!

    I have used Stack. Could you please tell me if this is one of the correct approach?

    
    public class Solution {
         StringBuilder sb = new StringBuilder();
         Stack st = new Stack();
        public String reverseWords(String s) {
             if(s.length()==0)
             {
                 return "";
             }
             for(int  i =0 ; i<s.length();i++)
             {
                 if(s.charAt(i)!=' ')
                     st.push(s.charAt(i));
                 else{
                     add();
                     sb.append(" ");
                 }
             }
              add();
            return sb.toString();
        }
        public void add()
        {
                while(!st.empty()){
                    sb.append(st.pop());
                }
        }
    }
    
    

    Thank You


Log in to reply
 

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