Leetcode 58 Solution

This article provides solution to leetcode question 58 (length-of-last-word)

https://leetcode.com/problems/length-of-last-word

Solution

class Solution {
public:
    int lengthOfLastWord(string s) {
        int state = 0;
        int curr_len = 0;
        int last_len = 0;

        for (int i = 0; i < s.length(); i++)
        {
            auto ch = s[i];

            if (ch == ' ')
            {
                if (curr_len != 0)
                {
                    last_len = curr_len;
                    curr_len = 0;
                }
            }
            else
            {
                curr_len++;
            }
        }

        if (curr_len != 0)
            last_len = curr_len;

        return last_len;
    }
};