问题描述:
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”.
A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, “xxxx” has the interval [3,6].
A group is considered large if it has 3 or more characters.
Return the intervals of every large group sorted in increasing order by start index.
一个字符串里,有些字符连续出现。若一个字符连续出现的长度(次数)大于等于3,我们认为这组连续是长的,这时我们记录下这组连续字符的起始和终止脚标,加入到list中,返回list而且要保证脚标从小大大排列。
思路:
从左向右遍历可以保证输出是有序的。我们设立双指针,一个慢,一个快,慢的一开始指向0,快的一开始指向1 。 快的指针一步一步向前走,每一步检查是否与慢的指针指向的同一个字符,若相同则快的指针继续走(慢的指针不动),若不同则标志着此连续区间的结束,并计算连续区间的长度,若长度大于等于3则加入list,慢指针重设在快指针的位置,快指针加一(含在for循环里的)。注意最后的区间要手动结算。
代码如下:
class Solution {
public List<List<Integer>> largeGroupPositions(String s) {
int slower=0;
List<List<Integer>> ans=new ArrayList<>();
for(int faster=1; faster<s.length(); faster++){
//case1: when the faster char is different from the slower char, we need to end the curr session
if(s.charAt(slower)!=s.charAt(faster)){
//specially, if the length of the subpart is >=3, we add it to the list
if(faster-slower>=3){
List<Integer> list=new ArrayList<>();
list.add(slower);
list.add(faster-1);
ans.add(list);
}
slower=faster;
}
}
if(s.length()-1-slower+1>=3){
List<Integer> list=new ArrayList<>();
list.add(slower);
list.add(s.length()-1);
ans.add(list);
}
return ans;
}
}
时间复杂度:O(n)