码迷,mamicode.com
首页 > 其他好文 > 详细

1358. Number of Substrings Containing All Three Characters

时间:2020-02-25 13:10:02      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:substr   sts   NPU   enc   contain   str   i++   image   out   

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.
class Solution {
  public int numberOfSubstrings(String s) {
        int count[] = {0, 0, 0}, res = 0 , i = 0, n = s.length();
        for (int j = 0; j < n; ++j) {
            ++count[s.charAt(j) - ‘a‘];
            while (count[0] > 0 && count[1] > 0 && count[2] > 0)
                --count[s.charAt(i++) - ‘a‘];
            res += i;
        }
        return res;
    }
}

sliding window

技术图片

 

 

class Solution {
    public int numberOfSubstrings(String s) {
        int[] count = new int[3];
        int res = 0;
        
        for(int lo = -1, hi = 0; hi < s.length(); hi++){
            count[s.charAt(hi) - ‘a‘]++;
            while(count[0] > 0 && count[1] > 0 && count[2] > 0){
                res += s.length() - hi;
                --count[s.charAt(++lo) - ‘a‘];
            }
        }
        return res;
    }
}

 

1358. Number of Substrings Containing All Three Characters

标签:substr   sts   NPU   enc   contain   str   i++   image   out   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12360775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!