Java accepted solution, need some advice


  • 0
    Y
    public int lengthOfLastWord(String s) {
        int index = -1;
        if(s.equals("")) return 0;
        if(s.charAt(s.length() - 1) == ' ' && s.length() != 1) return lengthOfLastWord(s.substring(0, s.length() - 1));
        for(int i = s.length() -1; i >= 0; i--){
            if(s.charAt(i) == ' '){
                index = i;
                break;
            }
        }
        return s.length() - index - 1;
    }
    

    I don't understand why this algorithm runs too slow, can anyone give me a hint?


  • 0
    Y

    There may be several spaces at the end the string, so your method may be recursively called many times.
    And the String.substring(int, int) method is costly.


Log in to reply
 

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