LeetCode:3298. 统计重新排列后包含另一个字符串的子字符串数目 II(滑动窗口 Java)

目录

[3298. 统计重新排列后包含另一个字符串的子字符串数目 II](#3298. 统计重新排列后包含另一个字符串的子字符串数目 II)

题目描述:

实现代码与解析:

滑动窗口

原理思路:


3298. 统计重新排列后包含另一个字符串的子字符串数目 II

题目描述:

给你两个字符串 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 <= 106
  • 1 <= word2.length <= 104
  • word1word2 都只包含小写英文字母。

实现代码与解析:

滑动窗口

java 复制代码
class Solution {
    public long validSubstringCount(String word1, String word2) {
 
        if (word1.length() < word2.length()) {
            return 0;
        }
 
        int[] hash = new int[26];
        // 种类
        int cnt = 0;
        for (char c : word2.toCharArray()) {
            if (hash[c - 'a']++ == 0) cnt++;
        }
 
        int[] cur = new int[26];
 
        long res = 0;
        for (int l = 0, r = 0; r < word1.length(); r++) {
 
            if (++cur[word1.charAt(r) - 'a'] == hash[word1.charAt(r) - 'a']) {
                cnt--;
            }
            while (cnt == 0) {
                if (cur[word1.charAt(l) - 'a'] == hash[word1.charAt(l) - 'a']) {
                    cnt++;
                }
                cur[word1.charAt(l) - 'a']--;
                l++;
            }
            res += l;
 
        }
        return res;
    }
}

原理思路:

与昨日同。LeetCode:3297. 统计重新排列后包含另一个字符串的子字符串数目 I(滑动窗口 Java)-CSDN博客

相关推荐
belhomme35 分钟前
(面试题)Netty 线程模型
java·面试·netty
曲幽1 小时前
FastAPI + PostgreSQL 实战:给应用装上“缓存”和“日志”翅膀
redis·python·elasticsearch·postgresql·logging·fastapi·web·es·fastapi-cache
xlp666hub4 小时前
Leetcode第七题:用C++解决接雨水问题
c++·leetcode
Lupino4 小时前
别再只聊 AI 写代码了:技术负责人要把“变更治理”提到第一优先级
python·docker·容器
NE_STOP5 小时前
MyBatis-plus进阶之映射与条件构造器
java
Flittly6 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(6)Context Compact (上下文压缩)
python·agent
Seven977 小时前
NIO的零拷贝如何实现高效数据传输?
java
曲幽17 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805121 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
架构师沉默1 天前
别又牛逼了!AI 写 Java 代码真的行吗?
java·后端·架构