Easy to understand C++ solution with comments


  • 0
    M
    class Solution {
    public:
        bool validWordAbbreviation(string word, string abbr) {
            
            int i = 0;
            int j = 0;
            
            int m = word.length();
            int n = abbr.length();
            
            // If abbr length > word length
            if(n > m)
                return false;
            
            while(i<m && j<n)
            {
                // Check if abbr and word index contains chars
                if(isalpha(word[i]) && isalpha(abbr[j]))
                {
                    if(word[i] != abbr[j])
                        return false;
                    i++;
                    j++;
                }
                
                else if(!isalpha(abbr[j]))
                {
                    // If first occurrence of digit is 0
                    if(abbr[j] == '0')
                        return false;
                    
                    int skip = 0;
                    while(abbr[j]>= '0' && abbr[j] <= '9')
                    {
                        skip = skip * 10 + (abbr[j]-'0');
                        j++;
                    }
                    
                    i = i + skip;
                }
            }
            
            return (i == m && j == n);
            
        }
    };
    

Log in to reply
 

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