以下是 LeetCode 3298 的 Rust 实现使用滑动窗口算法rustimpl Solution {pub fn valid_substring_count(word1: String, word2: String) - i64 {if word1.len() word2.len() {return 0;}// 统计 word2 中每个字符的需求量let mut need [0i32; 26];let mut required 0i32; // 还需要满足的字符种类数for c in word2.bytes() {let idx (c - ba) as usize;if need[idx] 0 {required 1;}need[idx] 1;}let word1 word1.as_bytes();let mut cur [0i32; 26]; // 当前窗口中各字符的数量let mut res: i64 0;let mut l 0usize;for r in 0..word1.len() {let rc (word1[r] - ba) as usize;cur[rc] 1;if cur[rc] need[rc] {required - 1; // 该字符需求已满足}// 当窗口满足所有字符需求时收缩左边界while required 0 {let lc (word1[l] - ba) as usize;if cur[lc] need[lc] {required 1; // 移出后将不再满足}cur[lc] - 1;l 1;}// 以 r 结尾的合法子串数量 l左边界可以取 0 ~ l-1res l as i64;}res}}关键点要点 说明word1.as_bytes() Rust 中将字符串转为字节数组用 u8 遍历避免 Unicode 多字节问题ba 字节字面量等价于 a as u8用于快速计算字符索引[0i32; 26] 固定大小数组类型标注为 i32 以匹配 required 的运算i64 返回 题目要求返回 longRust 中对应 i64复杂度- 时间复杂度O(n)每个字符最多被左右指针各访问一次- 空间复杂度O(1)只使用两个长度为 26 的固定数组与 Java/TypeScript 的区别Rust 版本使用 bytes() 和 as_bytes() 处理 ASCII 字符性能更优。滑动窗口的核心逻辑与 Java/TypeScript 完全一致都是找到以每个 r 结尾的最短合法窗口然后累加 l 作为合法左边界数量。
Kimi LeetCode 3298. 统计重新排列后包含另一个字符串的子字符串数目 II Rust实现
发布时间:2026/6/20 9:29:14
以下是 LeetCode 3298 的 Rust 实现使用滑动窗口算法rustimpl Solution {pub fn valid_substring_count(word1: String, word2: String) - i64 {if word1.len() word2.len() {return 0;}// 统计 word2 中每个字符的需求量let mut need [0i32; 26];let mut required 0i32; // 还需要满足的字符种类数for c in word2.bytes() {let idx (c - ba) as usize;if need[idx] 0 {required 1;}need[idx] 1;}let word1 word1.as_bytes();let mut cur [0i32; 26]; // 当前窗口中各字符的数量let mut res: i64 0;let mut l 0usize;for r in 0..word1.len() {let rc (word1[r] - ba) as usize;cur[rc] 1;if cur[rc] need[rc] {required - 1; // 该字符需求已满足}// 当窗口满足所有字符需求时收缩左边界while required 0 {let lc (word1[l] - ba) as usize;if cur[lc] need[lc] {required 1; // 移出后将不再满足}cur[lc] - 1;l 1;}// 以 r 结尾的合法子串数量 l左边界可以取 0 ~ l-1res l as i64;}res}}关键点要点 说明word1.as_bytes() Rust 中将字符串转为字节数组用 u8 遍历避免 Unicode 多字节问题ba 字节字面量等价于 a as u8用于快速计算字符索引[0i32; 26] 固定大小数组类型标注为 i32 以匹配 required 的运算i64 返回 题目要求返回 longRust 中对应 i64复杂度- 时间复杂度O(n)每个字符最多被左右指针各访问一次- 空间复杂度O(1)只使用两个长度为 26 的固定数组与 Java/TypeScript 的区别Rust 版本使用 bytes() 和 as_bytes() 处理 ASCII 字符性能更优。滑动窗口的核心逻辑与 Java/TypeScript 完全一致都是找到以每个 r 结尾的最短合法窗口然后累加 l 作为合法左边界数量。