Check Word Abbreviation
这题算法就是模拟,实现没有任何难度,唯一麻烦就是各种各样奇诡的boundary case导致很难一次性bug free搞定,这里只是把比较好懂的一段代码放上来,碰到也只能背板了如果想bug free的话
class Solution(object):
def validWordAbbreviation(self, word, abbr):
"""
:type word: str
:type abbr: str
:rtype: bool
"""
cur_abrr = 0
cur_word = 0
n = len(word)
m = len(abbr)
while cur_abrr < m:
if abbr[cur_abrr].isalpha():
if abbr[cur_abrr] != word[cur_word]: # 直接字符对应不相等
return False
cur_abrr += 1
cur_word += 1
elif abbr[cur_abrr] == '0': # 缩写串里面有先导0不符合题意
return False
else:
tmp = 0
while cur_abrr < m and abbr[cur_abrr].isdigit():
tmp = 10 * tmp + ord(abbr[cur_abrr]) - ord('0')
cur_abrr += 1
cur_word += tmp
if cur_word > n or (cur_word == n and cur_abrr < m): # 考虑原字串已经超过终点值以及原字串到达终点但缩写串没有
return False
return True if cur_word == n and cur_abrr == m else False # 最后以防万一再check一遍是不是同时到达了终点
放一种相对简洁一点的版本,这里主要是先导零的问题很烦,思路上还是one edit distance的改版
class Solution(object):
def validWordAbbreviation(self, word, abbr):
"""
:type word: str
:type abbr: str
:rtype: bool
"""
wordPt, abbrPt = 0, 0
n, m = len(word), len(abbr)
curNum = 0
while wordPt < n and abbrPt < m:
if abbr[abbrPt].isalpha():
wordPt += curNum
curNum = 0
if wordPt >= n or abbr[abbrPt] != word[wordPt]:
return False
wordPt += 1
else:
curNum = 10 * curNum + ord(abbr[abbrPt]) - ord('0')
if not curNum:
return False
abbrPt += 1
return wordPt + curNum == n and abbrPt == m