ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 1358. Number of Substrings Containing All Three Characters

2020-12-24 04:01:15  阅读:231  来源: 互联网

标签:count Containing 1358 end int Three start abc 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.

包含所有三种字符的子字符串数目。

给你一个字符串 s ,它只包含三种字符 a, b 和 c 。请你返回 a,b 和 c 都 至少 出现过一次的子字符串数目。

思路是滑动窗口。这道题的窗口卡的是一个子区间满足子区间内unique key的个数是3。同时因为input里只有abc三个字母,所以当你找到第一个子串的终点 end 的时候,子串[start, s.length - 1] 其实都是满足题意的子串,所以此时可以尝试移动 start 指针,只有count == 3的时候,我们才能移动 start 指针。这道题依然可以使用76题的模板

时间O(n)

空间O(1) - letter数组可以忽略不计

Java实现

 1 class Solution {
 2     public int numberOfSubstrings(String s) {
 3         int len = s.length();
 4         int[] letter = new int[3];
 5         int count = 0;
 6         int res = 0;
 7         int start = 0;
 8         int end = 0;
 9         while (end < s.length()) {
10             char c1 = s.charAt(end);
11             if (letter[c1 - 'a']++ == 0) {
12                 count++;
13             }
14             while (count == 3) {
15                 res += len - end;
16                 char c2 = s.charAt(start);
17                 if (letter[c2 - 'a']-- == 1) {
18                     count--;
19                 }
20                 start++;
21             }
22             end++;
23         }
24         return res;
25     }
26 }

 

sliding window相关题目

LeetCode 题目总结

标签:count,Containing,1358,end,int,Three,start,abc,characters
来源: https://www.cnblogs.com/cnoodle/p/14182375.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有