LeetCode 809 情感丰富的文字[双指针] HERODING的LeetCode之路

在这里插入图片描述

解题思路:
看完题目就很容易想到双指针,将s与每个word进行比较,用两个指针分别指向两个单词,比较对应位置是否相等,连续相等字母的expand是否超过3,比较过程封装成函数返回true或者false,代码如下:

class Solution {
public:
    int expressiveWords(string s, vector<string>& words) {
        int res = 0;
        for(auto& word : words) {
            if(expand(s, word)) {
                res ++;
            }
        } 
        return res;
    }

    bool expand(string& s, string& word) {
        int n1 = s.size(), n2 = word.size();
        int index1 = 0, index2 = 0;
        while(index1 < n1 && index2 < n2) {
            // 对应位置不相等
            if(s[index1] != word[index2]) {
                return false;
            }
            char c = s[index1];
            int count1 = 0;
            while(index1 < n1 && s[index1] == c) {
                count1 ++;
                index1 ++;
            }
            int count2 = 0;
            while(index2 < n2 && word[index2] == c) {
                count2 ++;
                index2 ++;
            }
            // 如果扩张还不如没扩张
            if(count1 < count2) {
                return false;
            }
            // 扩张了但是不够数
            if(count1 != count2 && count1 < 3) {
                return false;
            }
        }
        return index1 == n1 && index2 == n2;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HERODING77

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值