LeetCode-Python-408. 有效单词缩写

字符串可以用 缩写 进行表示,缩写 的方法是将任意数量的 不相邻 的子字符串替换为相应子串的长度。例如,字符串 "substitution" 可以缩写为(不止这几种方法):

  • "s10n" ("s ubstitutio n")
  • "sub4u4" ("sub stit u tion")
  • "12" ("substitution")
  • "su3i1u2on" ("su bst i t u ti on")
  • "substitution" (没有替换子字符串)

下列是不合法的缩写:

  • "s55n" ("s ubsti tutio n",两处缩写相邻)
  • "s010n" (缩写存在前导零)
  • "s0ubstitution" (缩写是一个空字符串)

给你一个字符串单词 word 和一个缩写 abbr ,判断这个缩写是否可以是给定单词的缩写。

子字符串是字符串中连续的非空字符序列。

示例 1:

输入:word = "internationalization", abbr = "i12iz4n"
输出:true
解释:单词 "internationalization" 可以缩写为 "i12iz4n" ("i nternational iz atio n") 。

示例 2:

输入:word = "apple", abbr = "a2e"
输出:false
解释:单词 "apple" 无法缩写为 "a2e" 。

提示:

  • 1 <= word.length <= 20
  • word 仅由小写英文字母组成
  • 1 <= abbr.length <= 10
  • abbr 由小写英文字母和数字组成
  • abbr 中的所有数字均符合 32-bit 整数范围

思路:

经典双指针,按题意扫描即可。

时间复杂度:O(M + N)

空间复杂度:O(1)

class Solution(object):
    def validWordAbbreviation(self, word, abbr):
        """
        :type word: str
        :type abbr: str
        :rtype: bool
        """
        # two pointers, one for word and one for abbr
        i, j = 0, 0
        while i < len(word) and j < len(abbr):
            if abbr[j].isalpha():
                if word[i] != abbr[j]:
                    return False
                i += 1
                j += 1
            else: # digits
                if abbr[j] == "0":
                    # leading 0
                    return False
                num = 0
                while j < len(abbr) and abbr[j].isdigit():
                    num = num * 10 + int(abbr[j])
                    j += 1
                i = i + num
        return i == len(word) and j == len(abbr)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值