408. Valid Word Abbreviation


做题历程:

  1. 2016/Oct/20,本次是第一次做,大致耗时15分钟独立解出

其实本题还是很简单的,就是以遍历为基础,唯一需要注意的一点是:碰到数字的话要看全,例如"12",不能只看见'1'就停止。 代码如下:

class Solution {
public:
    bool validWordAbbreviation(string word, string abbr) {
        int i = 0;
        for (int j = 0; j < abbr.length(); ++j) {
            if (isdigit(abbr[j]) && abbr[j] != '0') {
                int num = 0;
                while(j < abbr.length() && isdigit(abbr[j])) {
                    num = num * 10 + (abbr[j++] - '0');
                }
                i += num;
                --j;
            }
            else {
                if (abbr[j] != word[i]) {
                    return false;
                }
                ++i;
            }
        }
        return i == word.length();
    }
};

当然本题也能用Regular Expression解决,不过这里不采用。。

results matching ""

    No results matching ""