comments | difficulty | edit_url | tags | |||
---|---|---|---|---|---|---|
true |
中等 |
|
输入数据为两个字符串firstString
和 secondString
,两个字符串下标均从0开始,且均只包含小写的英文字符,请计算满足下列要求的下标四元组(i,j,a,b)
的个数:
0 <= i <= j < firstString.length
0 <= a <= b < secondString.length
firstString
字符串中从i
位置到j
位置的子串(包括j
位置的字符)和secondString
字符串从a
位置到b
位置的子串(包括b
位置字符)相等j-a
的数值是所有符合前面三个条件的四元组中可能的最小值
返回符合上述 4 个条件的四元组的 个数 。
示例1:
输入:firstString = "abcd", secondString = "bccda"
输出:1
解释:(0,0,4,4)是唯一符合条件的四元组且其j-a
的数值是最小的.
示例 2:
输入:firstString = "ab", secondString = "cd" 输出:0 解释:没有任何一个四元组能满足上述4个要求.
提示:
1 <= firstString.length, secondString.length <= 2 * 105
- 两个输入字符串均只包含小写英文字符.
题目实际上要我们找到一个最小的下标
因此,我们先用哈希表
时间复杂度
class Solution:
def countQuadruples(self, firstString: str, secondString: str) -> int:
last = {c: i for i, c in enumerate(secondString)}
ans, mi = 0, inf
for i, c in enumerate(firstString):
if c in last:
t = i - last[c]
if mi > t:
mi = t
ans = 1
elif mi == t:
ans += 1
return ans
class Solution {
public int countQuadruples(String firstString, String secondString) {
int[] last = new int[26];
for (int i = 0; i < secondString.length(); ++i) {
last[secondString.charAt(i) - 'a'] = i + 1;
}
int ans = 0, mi = 1 << 30;
for (int i = 0; i < firstString.length(); ++i) {
int j = last[firstString.charAt(i) - 'a'];
if (j > 0) {
int t = i - j;
if (mi > t) {
mi = t;
ans = 1;
} else if (mi == t) {
++ans;
}
}
}
return ans;
}
}
class Solution {
public:
int countQuadruples(string firstString, string secondString) {
int last[26] = {0};
for (int i = 0; i < secondString.size(); ++i) {
last[secondString[i] - 'a'] = i + 1;
}
int ans = 0, mi = 1 << 30;
for (int i = 0; i < firstString.size(); ++i) {
int j = last[firstString[i] - 'a'];
if (j) {
int t = i - j;
if (mi > t) {
mi = t;
ans = 1;
} else if (mi == t) {
++ans;
}
}
}
return ans;
}
};
func countQuadruples(firstString string, secondString string) (ans int) {
last := [26]int{}
for i, c := range secondString {
last[c-'a'] = i + 1
}
mi := 1 << 30
for i, c := range firstString {
j := last[c-'a']
if j > 0 {
t := i - j
if mi > t {
mi = t
ans = 1
} else if mi == t {
ans++
}
}
}
return
}
function countQuadruples(firstString: string, secondString: string): number {
const last: number[] = new Array(26).fill(0);
for (let i = 0; i < secondString.length; ++i) {
last[secondString.charCodeAt(i) - 97] = i + 1;
}
let [ans, mi] = [0, Infinity];
for (let i = 0; i < firstString.length; ++i) {
const j = last[firstString.charCodeAt(i) - 97];
if (j) {
const t = i - j;
if (mi > t) {
mi = t;
ans = 1;
} else if (mi === t) {
++ans;
}
}
}
return ans;
}