同端子串的数量
难度:
标签:
题目描述
代码结果
运行时间: 799 ms, 内存: 33.5 MB
/**
* Problem: Leetcode 2955 - Count Equal Substrings
*
* Idea: Using Java Streams, we can achieve the same goal by creating a stream
* of all possible substrings and then filtering those that have the same beginning
* and ending characters. This solution leverages streams and lambda expressions,
* providing a more functional approach.
*/
import java.util.stream.IntStream;
public class CountEqualSubstringsStream {
public long countEqualSubstrings(String s) {
int n = s.length();
return IntStream.range(0, n)
.mapToLong(i -> IntStream.range(i, n)
.filter(j -> s.charAt(i) == s.charAt(j))
.count())
.sum();
}
public static void main(String[] args) {
CountEqualSubstringsStream cess = new CountEqualSubstringsStream();
String s = "abcab";
System.out.println(cess.countEqualSubstrings(s)); // Output should be 7
}
}
解释
方法:
此题解采用前缀和数组来快速计算字符串中任意子串的字符频率。首先,构建一个前缀和数组counters,其中counters[i][j]表示字符串s中前i个字符中字符('a'+j)出现的次数。接着,对于每个查询,我们可以快速得到子串s[x...y]中每个字符的出现次数,然后计算每个字符能形成的同端子串的数量,即字符出现次数乘以该次数加一再除以二。最后,将这些数相加得到对应查询的结果。
时间复杂度:
O(n + q)
空间复杂度:
O(n)
代码细节讲解
🦆
在构建前缀和数组时,你是如何确保每个字符的计数是准确的?是否有可能出现计数误差?
▷🦆
前缀和数组counters的初始化为什么选择[[0]*26],这里代表的意义是什么?
▷🦆
在处理查询时,counters[y+1][i] - counters[x][i]的计算方式是如何确保能够准确得到子串s[x...y]中每个字符的计数的?
▷🦆
为什么每个字符能形成的同端子串的数量可以用公式v * (v + 1) // 2来计算?这里的逻辑基础是什么?
▷