Java Easy and Intuitive - Beats only 5.67%


  • 0
    V
    import java.util.regex.Pattern;
    public class Solution {
        public int lengthOfLastWord(String s) {
            if (s.isEmpty() || s.equals("")) return 0;
            String[] input = s.split(Pattern.quote(" "));
    	if (input.length == 0) return 0;
    	return input[input.length - 1].length();
        }
    }
    

    How do I improve runtime? I thought this was the minimal that was required!


  • 0
    P

    Maybe split isn't the best idea here since you have to go through the whole string to know where to split. String.lastIndexOf probably starts from the end, so you don't have to waste as much time (which is what I used)!


Log in to reply
 

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