1,题目要求
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.
对于一个给定的字符串,找出其中连续出现次数超过三次的子字符串,记录这个子字符串的开始和结束的索引位置,返回这样一个索引对序列。
2,题目思路
没有太多难点,用直接法来做是最快的。值得注意的是,直接(straight-forward)并不等同于暴力(brute)。暴力是在牺牲大量时间和空间基础之上的求解办法,而好的直接法是从问题的本质直接入手的办法,在性能上未必没有间接法要好。
对于这一题,只需要遍历整个字符串,并以此记录相邻字母出现的次数以及该字母的起始位置。当其出现次数大于等于3时,直接构造一个索引对并添加到最终解中即可。
3,程序源码
class Solution {
public:
vector<vector<int>> largeGroupPositions(string S) {
int count = 1,pos = 0;
vector<vector<int>> res;
for(int i = 0;i<S.size();i++)
{
vector<int> tmp (2,0);
if(S[i] == S[i+1])
count ++;
else
{
if(count>=3)
{
tmp[0] = pos;
tmp[1] = pos+ count - 1;
res.push_back(tmp);
}
pos = i+1;
count = 1;
}
}
return res;
}
};