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 Abbreviation和Generalized 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; } };
類似題目:
參考資料:
https://discuss.leetcode.com/topic/61404/concise-c-solution
https://discuss.leetcode.com/topic/61430/java-2-pointers-15-lines
https://discuss.leetcode.com/topic/61353/simple-regex-one-liner-java-python