clueless coding // TODO: be smarter

LeetCode Valid Word Abbreviation: CPP Solution



TL;DR Code Solution


bool validWordAbbreviation(string word, string abbr) {

    int wordIndex = 0;
    int abbrIndex = 0;

    while (wordIndex < word.length() && abbrIndex < abbr.length()) {

        if (word[wordIndex] == abbr[abbrIndex]) {
            wordIndex++; abbrIndex++;
        }    
        else {
            // 1. abbr[abbrIndex] was a number, which means part of an abbreviation
            if (isdigit(abbr[abbrIndex])) {
                if (abbr[abbrIndex] == '0') return false;
                // parse until integer, increment wordIndex
                int abbreviated = 0;
                for (; abbrIndex < abbr.length(); abbrIndex++) {
                    if (isdigit(abbr[abbrIndex])) {
                        abbreviated *= 10;
                        abbreviated += abbr[abbrIndex] - '0';                            
                    }
                    else {
                        break;
                    }
                }
                wordIndex += abbreviated;



            }
            // 2. abbr[abbrIndex] was a letter, which means that don't have a match
            else {
                return false;
            }
        }
    }

    return wordIndex == word.length() && abbrIndex == abbr.length();

}