• 情感丰富的文字


    题目链接

    情感丰富的文字

    题目描述

    注意

    • s 和所有在 words 中的单词都只由小写字母组成
    • 扩展操作定义:选择一个字母组(包含字母 c ),然后往其中添加相同的字母 c 使其长度达到 3 或以上

    解答思路

    • 使用双指针,一个指针指向s,一个指针指向word,对两个字符串进行遍历。观察规律统计出不符合题意的几种情况:
      (1)比较word和s的长度,如果word长度大于s,则该单词不满足题意;
      (2)如果任意一个指针已经遍历完相应的字符串而另一个指针未遍历完字符串,则该单词不满足题意;
      (3)如果两个指针此时指向的字符不相同,则该单词不满足题意;
      (4)如果两个指针此时指向的字符相同,但是该字符在两个字符串中的数量并不满足可扩展,则该单词不满足题意

    代码

    方法一:

    class Solution {
        public int expressiveWords(String s, String[] words) {
            int res = 0;
            for (String word : words) {
                if (word.length() > s.length()) continue;
                int idxS = 0, idxW = 0;
                boolean isExpand = true;
                while (idxS < s.length() || idxW < word.length()) {
                    if ((idxS == s.length() && idxW < word.length()) || (idxS < s.length() && idxW == word.length())) {
                        isExpand = false;
                        break;
                    }
                    // 如果此时的字符不同,则一定不满足
                    if (s.charAt(idxS) != word.charAt(idxW)) {
                        isExpand = false;
                        break;
                    }
                    char c = s.charAt(idxS);
                    int countS = 0, countW = 0;
                    while (idxS < s.length() && s.charAt(idxS) == c) {
                        idxS++;
                        countS++;
                    }
                    while (idxW < word.length() && word.charAt(idxW) == c) {
                        idxW++;
                        countW++;
                    }
                    if (countS == countW) continue;
                    if (countS < countW || countS < 3) {
                        isExpand = false;
                        break;
                    }
                }
                if (isExpand) res++;
            }
            return res;
        }
    
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    关键点

    • 统计出word不满足题意的几种情况并分类讨论
    • 注意越界问题
  • 相关阅读:
    51单总线控制SV-5W语音播报模块
    FFmpeg 音频解码(秒懂)
    对开源自动化测试平台MeterSphere的使用感触
    卡尔曼滤波器第 2 部分 - 贝叶斯滤波器
    前端研习录(20)——JavaScript三元运算符
    如何申请百度apikey
    ffmpeg 合并视频到一个画布
    selinux-policy-default(2:2.20231119-2)软件包内容详细介绍(2)
    项目申请理论理解---2022.8月
    【面试题 - mysql】进阶篇 - MVCC多版本并发控制原理
  • 原文地址:https://blog.csdn.net/weixin_51628158/article/details/128087012