1. 程式人生 > >LeetCode 830. Positions of Large Groups

LeetCode 830. Positions of Large Groups

出現 else osi fin all spa 字符串 ans XA

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