LeetCode 1358. Number of Substrings Containing All Three Characters
原题链接在这里:https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/description/
题目:
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
Constraints:
3 <= s.length <= 5 x 10^4
s
only consists of a, b or c characters.
题解:
Have walker and runner both move to the right. When all a, b, c count is larger than 0, move the walker.
res += walker is because there could be walker substrings fulfill the requirement.
e.g. aaabc, walker could move to 3, res += walker. Since there are 3 substrings aaabc, aabc and abc.
Time Complexity: O(n). n = s.length().
Space: O(1).
AC Java:
1 class Solution { 2 public int numberOfSubstrings(String s) { 3 int [] map = new int[3]; 4 int walker = 0; 5 int runner = 0; 6 int res = 0; 7 int n = s.length(); 8 while(runner < n){ 9 map[s.charAt(runner++) - 'a']++; 10 while(map[0] > 0 && map[1] > 0 && map[2] > 0){ 11 map[s.charAt(walker++) - 'a']--; 12 } 13 14 res += walker; 15 } 16 17 return res; 18 } 19 }