【从零开始的LeetCode-算法】3297. 统计重新排列后包含另一个字符串的子字符串数目 I

给你两个字符串 word1word2

如果一个字符串 x 重新排列后,word2 是重排字符串的 前缀,那么我们称字符串 x合法的

请你返回 word1合法 子字符串的数目。

示例 1:

**输入:**word1 = "bcca", word2 = "abc"

**输出:**1

解释:

唯一合法的子字符串是 "bcca" ,可以重新排列得到 "abcc""abc" 是它的前缀。

示例 2:

**输入:**word1 = "abcabc", word2 = "abc"

**输出:**10

解释:

除了长度为 1 和 2 的所有子字符串都是合法的。

示例 3:

**输入:**word1 = "abcabc", word2 = "aaabc"

**输出:**0

解释:

  • 1 <= word1.length <= 10^5
  • 1 <= word2.length <= 10^4
  • word1word2 都只包含小写英文字母。

我的解答

java 复制代码
class Solution {
    public long validSubstringCount(String word1, String word2) {
        int len1 = word1.length(), len2 = word2.length();
        // 记录word2中字母出现的次数
        int[] pre = new int[26];
        // 记录word2中的字母在word1中出现的次数
        int[] p = new int[26];
        for(char ch : word2.toCharArray()){
            pre[ch - 'a']++;
        }
        long res = 0;
        int left = 0;
        for(int i = 0; i < len1 ; i++){
            int ch = word1.charAt(i) - 'a';
            p[ch]++;
            if(pre[ch] > 0 && p[ch] <= pre[ch]) len2--;
            // 右遍历找到刚好包含word2中所有单词的子字符串后,收拢左边区域
            if(len2 <= 0){
                // 右边剩余单词可与当前字符串构成的组合
                long ans = len1 - i;
                long count = 0;
                while(left <= i){
                    int left_ch = word1.charAt(left) - 'a';
                    count++;
                    left++;
                    // 左边单词为前缀单词,则该单词数减1
                    if(pre[left_ch] > 0){
                        p[left_ch]--;
                        // 如果当前单词数量减1后不符合前缀条件,则退出循环,进行向右补充单词
                        if(p[left_ch] < pre[left_ch]){
                            len2++;
                            break;
                        }
                    }
                }
                res += ans * count;
            }
        }
        return res;
    }
}
相关推荐
冰敷逆向2 分钟前
京东h5st纯算分析
java·前端·javascript·爬虫·安全·web
咩咩不吃草16 分钟前
【逻辑回归】:从模型训练到评价
算法·机器学习·逻辑回归
ersaijun17 分钟前
机器人运动控制关键算法体系:从理论框架到前沿实践
算法·机器人
Coder_preston23 分钟前
Java集合框架详解
java·开发语言
smj2302_7968265226 分钟前
解决leetcode第3826题.最小分割分数问题
数据结构·python·算法·leetcode
多多*27 分钟前
2026年最新 测试开发工程师相关 Linux相关知识点
java·开发语言·javascript·算法·spring·java-ee·maven
树码小子37 分钟前
SpringIoC & DI (1):IOC介绍 & Spring IoC使用 & DI
java·后端·spring
VT.馒头38 分钟前
【力扣】2705. 精简对象
javascript·数据结构·算法·leetcode·职场和发展·typescript
元亓亓亓1 小时前
LeetCode热题100--136. 只出现一次的数字--简单
算法·leetcode·职场和发展
tb_first1 小时前
万字超详细苍穹外卖学习笔记5
java·数据库·spring boot·笔记·学习·spring