Java, StringBuilder, easy to understand


  • 0
    D
    public class Solution {
        public String reverseWords(String s) 
        {
            if (s == null) { return s; }
            
            // separate into words array
            String[] words = s.trim().split(" ");
            
            StringBuilder res = new StringBuilder();
            for (String w : words)
            {
                StringBuilder tmp = new StringBuilder(w);
                res.append(tmp.reverse()).append(" ");
            }
            // remove last space
            return res.toString().trim();
        }
    }
    

Log in to reply
 

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