LeetCode 830. Positions of Large Groups
Posted 皇家大鹏鹏
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 830. Positions of Large Groups相关的知识,希望对你有一定的参考价值。
In a string S
of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like S = "abbxxxxzyy"
has the groups "a"
, "bb"
, "xxxx"
, "z"
and "yy"
.
Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.
The final answer should be in lexicographic order.
Example 1:
Input: "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the single
large group with starting 3 and ending positions 6.
Example 2:
Input: "abc" Output: [] Explanation: We have "a","b" and "c" but no large group.
Example 3:
Input: "abcdddeeeeaabbbcd" Output: [[3,5],[6,9],[12,14]]
Note: 1 <= S.length <= 1000
这道题本质上是在求字符串中连续重复3次及以上的子串首位位置,看上去不难,其实还是有很多坑在里面。比较直接的思路就是从头到尾遍历,一边遍历一边统计,但是要注意——这个思路最大的坑就是当一个字符串最后的3个字符是重复的时,无法将其返回到答案中。比如测试用例为“bbbaaaaa”,或者“aaaa”最后4个a的统计结果无法被返回,我最开始的解决思路是单独枚举字符串末尾出现重复变量的例子,但是后来我发现情况太多根本没有办法枚举完。于是我在外层for循环上做了点修改,多遍历一次,在内部用个if做判断,问题得到解决
1 class Solution { 2 public: 3 vector<vector<int>> largeGroupPositions(string S) { 4 vector<vector<int>> res; 5 if (S.size() < 3) 6 return res; 7 /*if (S.size() == 3 && S[0] == S[1] && S[1] == S[2]) 8 { 9 res.push_back({ 0,2 }); 10 return res; 11 } 12 if (S.size() == 4 && S[0] == S[1] && S[1] == S[2] && S[2] == S[3]) 13 { 14 res.push_back({ 0,2 }); 15 return res; 16 }*/ 17 int start = 0; 18 int len = 0; // the length of group 19 for (int i = 0; i <= S.size(); i++) 20 { 21 //vector<int> temp; 22 if (i != S.size()) 23 { 24 if (S[i] == S[start]) 25 { 26 len++; 27 continue; 28 } 29 if (len >= 3) 30 { 31 res.push_back({ start,start + len - 1 }); 32 len = 1; 33 start = i; 34 } 35 else 36 { 37 len = 1; 38 start = i; 39 } 40 } 41 else 42 { 43 if (len >= 3) 44 res.push_back({ start,start + len - 1 }); 45 } 46 47 } 48 return res; 49 } 50 };
以上是关于LeetCode 830. Positions of Large Groups的主要内容,如果未能解决你的问题,请参考以下文章
830. Positions of Large Groups - LeetCode
[LeetCode&Python] Problem 830. Positions of Large Groups
Leetcode 830. Positions of Large Groups
830. Positions of Large Groups