Reverse the ordering of words in a string

后端 未结 30 4402
青春惊慌失措
青春惊慌失措 2020-11-22 10:23

I have this string s1 = \"My name is X Y Z\" and I want to reverse the order of the words so that s1 = \"Z Y X is name My\".

I can do it u

30条回答
  •  面向向阳花
    2020-11-22 11:09

    My version of using stack:

    public class Solution {
        public String reverseWords(String s) {
            StringBuilder sb = new StringBuilder();
            String ns= s.trim();
            Stack reverse = new Stack();
            boolean hadspace=false;
    
            //first pass
            for (int i=0; i< ns.length();i++){
                char c = ns.charAt(i);
                if (c==' '){
                    if (!hadspace){
                        reverse.push(c);
                        hadspace=true;
                    }
                }else{
                    hadspace=false;
                    reverse.push(c);
                }
            }
            Stack t = new Stack();
            while (!reverse.empty()){
                char temp =reverse.pop();
                if(temp==' '){
                    //get the stack content out append to StringBuilder
                    while (!t.empty()){
                        char c =t.pop();
                        sb.append(c);
                    }
                    sb.append(' ');
                }else{
                    //push to stack
                    t.push(temp);
                }
            }
            while (!t.empty()){
                char c =t.pop();
                sb.append(c);
            }
            return sb.toString();
        }
    }
    

提交回复
热议问题