Leetcode 1358 Number of Substrings Containing All Three Characters (滑动窗口)

Leetcode 1358

问题描述

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

方法一

** Solution Java **
** 6ms, beats 93.11% **
** 41.3MB, beats 100.00% **
class Solution {
    public int numberOfSubstrings(String s) {
        int n = s.length(), res = 0, k = 3;
        char[] S = s.toCharArray();
        int[] count = new int[3];
        for (int i = 0, j = 0; j < n; ++j) {
            ++count[S[j] - 'a'];
            while(count[0] > 0 && count[1] > 0 && count[2] > 0)
                --count[S[i++] - 'a'];
            res += i;
        }
        return res;
    }
}

方法二

** Solution Java **
** 4ms, 99.78% **
** 41.4MB, 100.00% **
class Solution {
    public int numberOfSubstrings(String s) {
        int last[] = {-1, -1, -1}, res = 0, n = s.length();
        char[] S = s.toCharArray();
        for (int i = 0; i < n; ++i) {
            last[S[i] - 'a'] = i;
            res += 1 + Math.min(last[0], Math.min(last[1], last[2]));
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/willwuss/p/12525753.html