Java split/stringbuffer solution, beat 78%


  • 0
    W

    Split() seems more intuitive, with some post processing during stringbuffer.append it works well.
    '''
    public String reverseWords(String s) {
    return reverseWords_split(s);
    }

    // Approach 1: split string into array of strings, then append into  
    private String reverseWords_split(String s){
        if (s== null || s.isEmpty()) return s;
        
        String[] str = s.trim().split(" ");
        if (str.length == 0) return new String("");
        
        StringBuffer sb = new StringBuffer(); 
        System.out.println("Num of strings: "+ str.length);
        for (int i = str.length -1; i >= 0; i--){
            // System.out.println("    string[" + i + "]" + str[i] + "," + " length =" + str[i].length());
            if (str[i].trim().length() > 0) {
                sb.append(str[i].trim());
                sb.append(" ");
            }
        }
        return sb.toString().trim();
    }
    

    ''''


  • 0
    W

    @whyseahike said in Java split/stringbuffer solution, beat 78%:

    simpler way to split on multiple whitespace is String[] str = s.trim().split("\s+");


Log in to reply
 

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