zoukankan      html  css  js  c++  java
  • 1358. Number of Substrings Containing All Three Characters

    package LeetCode_1358
    
    /**
     * 1358. Number of Substrings Containing All Three Characters
     * https://leetcode.com/problems/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).
    
    Constraints:
    1. 3 <= s.length <= 5 x 10^4
    2. s only consists of a, b or c characters.
     * */
    class Solution {
        /*
        * solution: Sliding window, Time complexity:O(n), Space complexity:O(1)
        * */
        fun numberOfSubstrings(s: String): Int {
            if (s == null || s.isEmpty()) {
                return 0
            }
            var result = 0
            //count the appearance of a,b,c
            val counter = IntArray(3)
            var left = 0
            var right = 0
            //the a,b,c count of substring
            var curCount = 0
            val n = s.length
            while (right < n) {
                val c = s[right]
                counter[c - 'a']++
                //if counter contains all a,b,c, reduce the window size
                while (left < n && counter[0] > 0 && counter[1] > 0 && counter[2] > 0) {
                    curCount++
                    val c2 = s[left]
                    counter[c2 - 'a']--
                    left++
                }
                //add to result
                result += curCount
                right++
            }
            return result
        }
    }
  • 相关阅读:
    property补充
    利用描述符自定制property
    类的装饰器
    上下文协议管理
    描述符
    迭代器协议
    doc属性__module__属性__del__(垃圾回收)__call__方法
    【移动支付】.NET支付宝App支付接入
    【WPF】PopupColorEdit 的使用
    【MVVM Dev】PART_Editor的使用
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13922684.html
Copyright © 2011-2022 走看看