My java solution, few lines.


  • 4
    C
    public class Solution {
        public String reverseWords(String s) {
            if(s == null) return "";
            
            int i = 0;
            String newStr = "";
            String word = "";
            while(i<s.length()){
                char c = s.charAt(i);
                if(c == ' '){
                    if(newStr != "" && word != "")
                        newStr = word + " " + newStr;
                    if(newStr == "" && word != "")
                        newStr = word;
                    word = "";
                }else{
                    word += c;
                }
                i++;
            }
            if(newStr != "" && word != "")
                newStr = word + " " + newStr;
            if(newStr == "" && word != "")
                newStr = word;
                
            return newStr;
        }
    }

  • 0
    S

    Pay attention to "Writing code? Select all code then click on the {} button to preserve code formatting.” above text editor.


  • 0
    O

    Everytime execute word += c there will be a new String object created. This will perform poorly. Better use StringBuilder.


  • 0
    C

    You are right, thanks.


  • 3
    L
    public class Solution {
        public String reverseWords(String s) {
            StringBuilder result = new StringBuilder();
            StringBuilder word = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) != ' ') {
                    word.append(s.charAt(i));
                } else {
                    if (word.length() > 0) {
                        result.insert(0, word.toString());
                        result.insert(0, " ");
                        word.setLength(0);
                    }
                }
            }
            if (word.length() > 0) {
                result.insert(0, word.toString());
            }
            if (result.length()>0 && result.charAt(0) == ' ') {
                return result.substring(1);
            }
            return result.toString();
        }
    }
    

    Share my java code using two stringbuilders, hasn't handled null case by the way.


  • 0
    Y

    you may need do it like this at last as below
    if (result.length()>0 && result.charAt(0) == ' '') {
    result.substring(1);
    }


  • 0
    L

    Nice catch, updated it.


Log in to reply
 

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