Short StringBuffer solution


  • 0
    public String reverseWords(String s) {
        StringBuffer sb = new StringBuffer(s);
        int startIdx = 0;
        for(int i=0; i<sb.length()+1; i++) {
            if(i==sb.length() || sb.charAt(i)==' ') {
                sb.replace(startIdx, i, new StringBuffer(sb.substring(startIdx,i)).reverse().toString());
                startIdx = i+1;
            }
        }
        return sb.toString();
    }

Log in to reply
 

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