Java solution


  • 0
    M
    public class Solution {
        public String reverseWords(String s) {
        String result = null;
        if(null == s || s.isEmpty()) {
            return "";
        } else {
            String[] temp = s.split(" ");
            if(temp.length > 0) {
                for(String st : temp) {
                    if(!st.isEmpty()) {
                        if(result == null) {
                            result = st;
                        } else {
                            result = st + " " + result;
                        }
                    }
                } 
            } else {
                result = "";
            }
        }
        return result;
        }
    }

  • 0
    S

    There is simpler answer.
    They say, its better to use StringBuffer instead '+' in cases you have a lot of iterations.

        public String reverseWords(String s) {
            String[] wordsArray = s.split(" "); 
            StringBuffer sb = new StringBuffer();
            
            for(int i = wordsArray.length-1; i >=0; i--){ 
                if(!wordsArray[i].isEmpty()){
                    sb.append(wordsArray[i]).append(' ');
                }
            }
            
            return sb.toString().trim();
        }
    }
    

  • 0
    K
    public void reverseWords(char[] s) {
        int i=0;
        for(int j=0; j<s.length; j++){
            if(s[j]==' '){
                reverse(s, i, j-1);        
                i=j+1;
            }
        }
     
        reverse(s, i, s.length-1);
     
        reverse(s, 0, s.length-1);
    }
     
    public void reverse(char[] s, int i, int j){
        while(i<j){
            char temp = s[i];
            s[i]=s[j];
            s[j]=temp;
            i++;
            j--;
        }
    }
    

Log in to reply
 

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