Solution by umeshp2003

  • 0

    Approach #2 Simple No loop solution [Accepted]


    A. Trim String S;
    B. set ind to value of index for the last occurrence of " ";
    C. if ind is -1 and String S is empty return 0;
    else if String s does not contain " " return s.length;
    else return the length of the substring of s starting at index ind


    public static int lengthOfLastWord(String s) {
    	s = s.trim();
    	int ind = s.lastIndexOf(' ');		
    	if(ind == -1 && s.isEmpty())
    	     return 0;
    	else if(!s.contains(" "))
    	     return s.length();
                 return s.substring(ind).trim().length();

    Complexity Analysis

    • Time complexity : $$O(1)$$. No loop.

Log in to reply

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