1. 程式人生 > >[LeetCode] Valid Word Abbreviation 驗證單詞縮寫

[LeetCode] Valid Word Abbreviation 驗證單詞縮寫

Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

A string such as "word" contains only the following valid abbreviations:

["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]

Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word".

Note:
Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

Example 1:

Given s = "internationalization", abbr = "i12iz4n":

Return true.

Example 2:

Given s = "apple", abbr = "a2e":

Return false.

這道題讓我們驗證單詞縮寫,關於單詞縮寫LeetCode上還有兩道相類似的題目Unique Word AbbreviationGeneralized Abbreviation。這道題給了我們一個單詞和一個縮寫形式,讓我們驗證這個縮寫形式是否是正確的,由於題目中限定了單詞中只有小寫字母和數字,所以我們只要對這兩種情況分別處理即可。我們使用雙指標分別指向兩個單詞的開頭,迴圈的條件是兩個指標都沒有到各自的末尾,如果指向縮寫單詞的指標指的是一個數字的話,如果當前數字是0,返回false,因為數字不能以0開頭,然後我們要把該數字整體取出來,所以我們用一個while迴圈將數字整體取出來,然後指向原單詞的指標也要對應的向後移動這麼多位數。如果指向縮寫單詞的指標指的是一個字母的話,那麼我們只要比兩個指標指向的字母是否相同,不同則返回false,相同則兩個指標均向後移動一位,參見程式碼如下:

解法一:

class Solution {
public:
    bool validWordAbbreviation(string word, string abbr) {
        int i = 0, j = 0, m = word.size(), n = abbr.size();
        while (i < m && j < n) {
            if (abbr[j] >= '0' && abbr[j] <= '9') {
                if (abbr[j] == '0') return false;
                int val = 0;
                while (j < n && abbr[j] >= '0' && abbr[j] <= '9') {
                    val = val * 10 + abbr[j++] - '0';
                }
                i += val;
            } else {
                if (word[i++] != abbr[j++]) return false;
            }
        }
        return i == m && j == n;
    }
};

下面這種方法和上面的方法稍有不同,這裡是用了一個for迴圈來遍歷縮寫單詞的所有字元,然後用一個指標p來指向與其對應的原單詞的位置,然後cnt表示當前讀取查出來的數字,如果讀取的是數字,我們先排除首位是0的情況,然後cnt做累加;如果讀取的是字母,那麼指標p向後移動cnt位,如果p到超過範圍了,或者p指向的字元和當前遍歷到的縮寫單詞的字元不相等,則返回false,反之則給cnt置零繼續迴圈,參見程式碼如下:

解法二:

class Solution {
public:
    bool validWordAbbreviation(string word, string abbr) {
        int m = word.size(), n = abbr.size(), p = 0, cnt = 0;
        for (int i = 0; i < abbr.size(); ++i) {
            if (abbr[i] >= '0' && abbr[i] <= '9') {
                if (cnt == 0 && abbr[i] == '0') return false;
                cnt = 10 * cnt + abbr[i] - '0';
            } else {
                p += cnt;
                if (p >= m || word[p++] != abbr[i]) return false;
                cnt = 0;
            }
        }
        return p + cnt == m;
    }
};

類似題目:

參考資料: