标题:Number of Substrings Containing All Three Characters
题目:
Given a string s
consisting only of characters a, b and c.
Return the number of substrings containing at least one occurrence of all these characters a, b and c.
Example 1:
Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again).
Example 2:
Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb".
Example 3:
Input: s = "abc" Output: 1
Constraints:
3 <= s.length <= 5 x 10^4
s
only consists of a, b or c characters.
解题思路:用一个指针对字符串进行从前往后遍历,记录最后一个包含a, b, c的最短子序列,如字符串“abcabc”, 指针指向位置4 ‘b’时,最后一个包含a,b,c的子序列是“abcabc” -> "cab",开始位置在2,‘c’。则以位置4结束的符合条件子序列个数为2+1=3,分别为:"cab", "bcab", "abcab"。
实现:用一个长度为3整型数组位置0保存最后一个'a'出现的位置,位置1保存最后一个'b'出现的位置,位置3保存最后一个'c'出现的位置。遍历到位置i时,如果位置i字符为'a',则找到前面的'b', 'c'最小位置start。最后结果加上start+1, 以此类推。代码如下:
class Solution {
public:
int numberOfSubstrings(string s) {
vector<int> pos(3, -1);
int res = 0;
for(int i = 0; i < s.length(); i++) {
int idx = s[i] - 'a';
pos[idx] = i;
int start = min(pos[(idx+1)%3], pos[(idx+2)%3]);
if (start > -1){
res += start+1;
}
}
return res;
}
};
时间复杂度O(N), 空间复杂度O(1)。