题目描述
在一个由小写字母构成的字符串s中,包含由一些连续的相同字符所构成的分组。
例如,在字符串S="abbxxxxzyy"中,就含有"a","bb","xxxx","z"和"yy"这样的一些分组。
我们称所有包含大于或等于三个连续字符的分组为较大分组。找到每一个较大分组的起始和终止位置。
最终结果按照字典顺序输出。
思路
简单题,注意边界条件即可。
C++代码
class Solution {
public:
/**
* @param s: a string
* @return: the starting and ending positions of every large group
*/
vector<vector<int>> largeGroupPositions(string &s) {
// Write your code here
if (s.size() <= 2) {
return std::vector<std::vector<int>>({});
} else {
std::vector<std::vector<int>> result;
int count = 1;
std::vector<int> tempVec = {0, 0};
char tempChar = s[0];
for (int i = 1; i < s.size(); ++i) {
if (s[i] != tempChar) {
if (count >= 3) {
tempVec[1] = i - 1;
result.push_back(tempVec);
}
tempVec[0] = i;
tempChar = s[i];
count = 1;
} else {
++count;
if (i == s.size() - 1 && count >= 3) {
tempVec[1] = i;
result.push_back(tempVec);
}
}
}
return result;
}
}
};