Leetcode 408 Solution

This article provides solution to leetcode question 408 (valid-word-abbreviation)

https://leetcode.com/problems/valid-word-abbreviation

Solution

class Solution {
public:
    bool validWordAbbreviation(string word, string abbr) {
        int i = 0;
        int j = 0;

        while (i < word.size() && j < abbr.size())
        {
            if (isdigit(abbr[j]) == false)
            {
                if (word[i] != abbr[j])
                    return false;

                i++, j++;
            }
            else
            {
                int k = j;
                while (k < abbr.size() && isdigit(abbr[k]))
                    k++;

                int len = atoi(abbr.substr(j, k - j).c_str());
                if (len == 0 || to_string(len) != abbr.substr(j, k - j))
                    return false;

                i += len;
                j = k;
            }
        }

        return i == word.size() && j == abbr.size();
    }
};