可整除子串的数量
难度:
标签:
题目描述
代码结果
运行时间: 109 ms, 内存: 16.4 MB
/*
* Leetcode 2950: Number of Divisible Substrings
* Given a string s, return the number of substrings of s that are divisible by k.
*
* Approach using Java Streams:
* 1. Generate all substrings of s using IntStream.
* 2. Filter the substrings that are divisible by k.
* 3. Count the number of valid substrings.
*/
import java.util.stream.IntStream;
public class Solution {
public long countDivisibleSubstrings(String s, int k) {
return IntStream.range(0, s.length())
.boxed()
.flatMap(i -> IntStream.range(i + 1, s.length() + 1)
.mapToObj(j -> s.substring(i, j)))
.filter(subStr -> !subStr.isEmpty() && Integer.parseInt(subStr) % k == 0)
.count();
}
}
解释
方法:
题解中包含两种方法。第一种方法使用了前缀和和哈希表的技术,将问题转化为求和为特定值的子数组数量。具体来说,对于每个可能的均值mean从1到9,计算数组中每个元素减去mean的结果,然后使用前缀和和哈希表来找出和为0的子数组数量。第二种方法是通过枚举所有可能的子串,对每个子串计算其元素映射值的总和,并检查这个总和是否可以被子串的长度整除,是则计数增加。
时间复杂度:
第一种方法O(n),第二种方法O(n^2)
空间复杂度:
第一种方法O(n),第二种方法O(1)
代码细节讲解
🦆
在使用前缀和和哈希表的方法中,为什么选择遍历均值mean从1到9,这里的数字范围是如何确定的?
▷🦆
在第一种方法中,前缀和哈希表是如何帮助我们找到和为0的子数组的?具体的工作原理是什么?
▷🦆
对于第二种方法,通过枚举所有子串来检查其映射值总和能否被子串长度整除,这种方法是否会因为子串较长时显得效率低下?
▷🦆
在第一种方法中,每次发现前缀和已存在于哈希表中时,为什么可以直接使用哈希表中的计数来增加结果?
▷