
Problem
Solution
Initial thoughts
Python implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class : def largeGroupPositions(self, S): """ :type S: str :rtype: List[List[int]] """ start = 0 end = 0 ans = [] for i in range(1, len(S)): if S[i] == S[i-1]: end = i else: if end - start >= 2: ans.append([start, end]) start = i if end - start >= 2: ans.append([start, end]) return ans
|
Java implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
class { public List<List<Integer>> largeGroupPositions(String S) { int start = 0; int end = 0; List<List<Integer>> ans = new ArrayList(); for(int i = 1; i < S.length(); i++){ if(S.charAt(i-1)==S.charAt(i)){ end = i; }else{ if(end-start>=2){ ans.add(Arrays.asList(new Integer[]{start, end})); } start = i; } } if(end-start>=2){ ans.add(Arrays.asList(new Integer[]{start, end})); } return ans; } }
|
Time complexity
O(n).
Space complexity
O(n).
Links
830. Positions of Large Groups
(中文版) 算法笔记: 力扣#830 较大分组的位置
近期评论