LeetCode 1358. Number of Substrings Containing All Three Characters(2025/3/11 每日一题)

标题:Number of Substrings Containing All Three Characters

题目: 

Given a string s consisting only of characters ab and c.

Return the number of substrings containing at least one occurrence of all these characters ab and c.

Example 1:

Input: s = "abcabc"
Output: 10
Explanation: The substrings containing at least one occurrence of the characters ab 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 ab 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 ab or 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)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值