Concise Java


  • 0
    J
    1. Split string into tokens (separated by spaces)
    2. Reverse each token, and append to StringBuilder
    3. Profit
    public class Solution {
        public String reverseWords(String s) {
            if (s.length() == 0) return "";
            String[] tokens = s.split("\\s");
            StringBuilder ans = new StringBuilder();
            
            for (String str : tokens) {
                for (int i = str.length() - 1; i >= 0; i--) {
                    ans.append(str.charAt(i));
                }
                ans.append(" ");
            } 
            ans.deleteCharAt(ans.length() - 1);
    
            return ans.toString();
        }
    }

Log in to reply
 

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