• 1358. 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.
    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;
        }
    }
  • 相关阅读:
    ubuntu下安装配置apache2(含虚拟主机配置)
    ubuntu安装软件包apt-get和dpkg方法
    python日期,时间函数
    python多线程
    截取utf8中文字符串
    python解析json
    sqlite读写
    lambda,map,filter,reduce
    pyinstaller生成exe可执行程序
    对象练习
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12360775.html
Copyright © 2020-2023  润新知