Leetcode 809. Expressive Words

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Expressive Words

2. Solution

**解析:**Version 1,依次按顺序统计s与各个单词的字母个数,如果相同顺序(连续相等字母算顺序中的一位)的字母不相等,则不符合条件,如果s的字母个数小于3s与单词的字母个数不等,不符合条件,如果s的字母个数大于等于3且小于单词的字母个数,不符合条件,执行到某个字符串结束,如果没都达到最后,则不符合条件,否则满足条件。Version 2只统计s一次,然后再比对。

  • Version 1
class Solution:
    def expressiveWords(self, s: str, words: List[str]) -> int:
        count = 0
        n = len(s)
        for word in words:
            if self.check(word, s):
                count += 1
        return count


    def check(self, word, s):
        n = len(s)
        m = len(word)
        if m > n:
            return False
        i = 0
        j = 0
        while i < n and j < m:
            if s[i] != word[j]:
                return False
            t1 = 1
            t2 = 1
            while i < n - 1 and s[i] == s[i+1]:
                t1 += 1
                i += 1
            while j < m - 1 and word[j] == word[j+1]:
                t2 += 1
                j += 1
            if (t1 < 3 and t1 != t2) or t1 < t2:
                return False
            i += 1
            j += 1
        return i == n and j == m
  • Version 2
class Solution:
    def expressiveWords(self, s: str, words: List[str]) -> int:
        count = 0
        n = len(s)
        stat = []
        i = 0
        while i < n:
            temp = 1
            while i < n - 1 and s[i] == s[i+1]:
                temp += 1
                i += 1
            stat.append((s[i], temp))
            i += 1
        for word in words:
            m = len(word)
            if m > n:
                continue
            if self.check(word, stat):
                count += 1
        return count


    def check(self, word, stat):
        m = len(word)
        i = 0
        j = 0
        while j < m and i < len(stat):
            if stat[i][0] != word[j]:
                return False
            temp = 1
            while j < m - 1 and word[j] == word[j+1]:
                temp += 1
                j += 1
            if (stat[i][1] < 3 and stat[i][1] != temp) or stat[i][1] < temp:
                return False
            i += 1
            j += 1
        return i == len(stat)

Reference

  1. https://leetcode.com/problems/expressive-words/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值