Java Solution (2 method)


  • 0

    1st O(n)

    public class Solution {
        public String reverseWords(String s) {
            int len=s.length();
            StringBuilder newS=new StringBuilder();
            char tmp;
            int index=0;
            for(int i=0;i<len;i++){
                tmp=s.charAt(i);
                if(tmp==' '){
                    index=i;
                    newS.insert(index,tmp);
                    index++;
                    continue;
                }
                
                newS.insert(index,tmp);
            }
            
            return newS.toString();
        }
    }
    

    2nd O(2n)

    public class Solution {
        public String reverseWords(String s) {
            StringBuilder sb=new StringBuilder(s);
            String[] words=sb.reverse().toString().split(" ");
            StringBuilder newS=new StringBuilder();
            for(int i=words.length-1;i>=0;i--){
                newS.append(words[i]);
                if(i!=0) newS.append(" ");
            }
            
            return newS.toString();
        }
    }
    

Log in to reply
 

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