Don't forget to use StringBuilder in Java


  • 0
    J
    public class Solution {
        public String reverseWords(String s) {
            if(s == null || s.length() == 0) return "";
            String[] words = s.trim().split("\\s+");
            StringBuilder res = new StringBuilder();
            for(int i = words.length - 1; i >=0 ; i--){
                res.append(words[i]);
                if(i != 0) res.append(' ');
            }
            return res.toString();
        }
    }
    

    We can use some basic String API (I think this is allowed during interview). Don't use '+' operator. Because String in Java is immutable, '+' returns a new string every time in the loop. StringBuilder is more memory efficient.


  • 0
    S

    stringbuffer better' s StringBuilder


  • 0
    J

    Well, StringBuilder is faster than StringBuffer because it's not synchronized.


Log in to reply
 

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