Problem
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
Solution: Brute Force
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua // Running time: 18 ms class Solution { public: vector<vector<int>> largeGroupPositions(string S) { constexpr int kLargeGroupSize = 3; const int n = S.size(); vector<vector<int>> ans; int c = 0; for (int i = 0; i <= n; ++i, ++c) { if (i == n || S[i] != S[i - 1]) { if (c >= kLargeGroupSize) ans.push_back({i - c, i - 1}); c = 0; } } return ans; } }; |