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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2016-04-03 LintCode Longest Common Substring
2016-04-03 LintCode Longest Common Subsequence
2016-04-03 LeetCode 322. Coin Change
2016-04-03 LeetCode 339. Nested List Weight Sum