Java Solution, StringBuilder


  • 2
    public class Solution {
        public String reverseWords(String s) {
            StringBuilder sb = new StringBuilder();
            
            int i = 0, j = 0;
            while (i < s.length()) {
                if (s.charAt(i) == ' ') {
                    sb.append(" ");
                    i++;
                }
                else {
                    j = i + 1;
                    while (j < s.length() && s.charAt(j) != ' ') j++;
                    sb.append((new StringBuilder(s.substring(i, j))).reverse());
                    i = j;
                }
            }
            
            return sb.toString();
        }
    }
    

  • 6
    N

    What about this !

            StringBuilder sb = new StringBuilder();
            String[] str = s.split(" ");
    
            for (String ss : str) {
                sb.append(new StringBuilder(ss).reverse()).append(" ");
            }
            sb.deleteCharAt(sb.length()-1);
            return sb.toString();
    

  • 2

    @namespace Just another version haha...I don't think StringBuilder reverse() and String trim() are allowed in a real interview though.

    public class Solution {
        public String reverseWords(String s) {
            if (s == null || s.length() < 1) return s;
            StringBuilder sb = new StringBuilder();
            for (String str : s.split(" ")) {
                sb.append(" ").append(new StringBuilder(str).reverse());
            }
            return sb.toString().trim();
        }
    }
    

Log in to reply
 

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