leetcode-cn Daily Challenge on January 5th, 2021.
Difficulty : Easy
Related Topics : Array
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.
Input: s = "abbxxxxzzy" Output: [[3,6]] Explanation: "xxxx" is the only large group with start index 3 and end index 6.
Input: s = "abc" Output: [] Explanation: We have groups "a", "b", and "c", none of which are large groups.
Input: s = "abcdddeeeeaabbbcd" Output: [[3,5],[6,9],[12,14]] Explanation: The large groups are "ddd", "eeee", and "bbb".
Input: s = "aba" Output: []
1 <= s.length <= 1000
s
contains lower-case English letters only.
- mine
- Java
Runtime: 2 ms, faster than 37.20%, Memory Usage: 39.1 MB, less than 76.81% of Java online submissions
public List<List<Integer>> largeGroupPositions(String s) { List<List<Integer>> res = new ArrayList<>(); int t = 0; char[] arr = s.toCharArray(); for(int i = 0; i < arr.length; i++){ if(i == 0){ t++; }else{ if(arr[i] == arr[i - 1]){ t++; }else{ if(t >= 3){ res.add(Arrays.asList(i - t, i - 1)); } t = 1; } } if(i + 1 == arr.length && t >= 3){ res.add(Arrays.asList(i + 1 - t, i)); } } return res; }
- Java