Problem Statement

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5

Example 2:

Input: s = " "
Output: 0

Constraints:

Problem Link

Length of Last Word - LeetCode

Code

class Solution {
public:
    int lengthOfLastWord(string s) {
        
        int n = s.size();
        int len = 0;
        for(int i=0;i<n;i++)
        {
            len++;
            if(s[i]==' ')
            {
                while(i<n&&s[i]==' ')//skipping spaces
                    i++;
                
                if(i==n)//if we traversed the entire string
                    return len-1;//len-1 because 1 has been added before the if staement for the first space encountered
                else
                    len = 1;//because we saw non space char
            }
        }
        return len;
    }
};