Java: simple solution without trim() and split()


  • 0
    H
    public int lengthOfLastWord(String s) {
        int n = s.length();
        if(n < 1) return 0;
        int count = 0, previous = 0;
    
        for(int i = 0; i < n; i++)
        {
        	if(s.charAt(i) == ' ')
        	{
        		previous = count > 0 ? count : previous;
        		count = 0;
        	}
        	else count++;
        }
        return s.charAt(n - 1) == ' ' ? previous : count;
    }

Log in to reply
 

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