描述
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.
Example 1:
Input: "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the single large group with starting 3 and ending positions 6.
Example 2:
Input: "abc"
Output: []
Explanation: We have "a","b" and "c" but no large group.
Example 3:
Input: "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Note:
1 <= S.length <= 1000
解析
根据题意,设置两个变量 i 和 j,j 比 i 快,在遍历整个字符串的过程中,如果满足成为 group 的条件,就将 (i,j) 加入结果列表中,时间复杂度为 O(N),空间复杂度为 O(N)。
解答
class Solution(object):
def largeGroupPositions(self, S):
"""
:type S: str
:rtype: List[List[int]]
"""
if len(S)<3:
return []
i = 0
j = 1
res = []
while i<j and j<len(S):
if S[i] == S[j]:
j+=1
else:
if j-i>=3:
res.append([i,j-1])
i = j
j = i+1
else:
i = j
j = i+1
if j-i>=3:
res.append([i,j-1])
return res
运行结果
Runtime: 24 ms, faster than 81.94% of Python online submissions for Positions of Large Groups.
Memory Usage: 11.9 MB, less than 6.11% of Python online submissions for Positions of Large Groups.
解析
根据题意,另一种思路类似,就是代码比较简单,时间复杂度为 O(N),空间复杂度为 O(N)。
解答
class Solution(object):
def largeGroupPositions(self, S):
"""
:type S: str
:rtype: List[List[int]]
"""
res = []
i = 0
for j in range(len(S)):
if j==len(S)-1 or S[j]!=S[j+1]:
if j-i+1>=3:
res.append([i,j])
i=j+1
return res
运行结果
Runtime: 28 ms, faster than 62.57% of Python online submissions for Positions of Large Groups.
Memory Usage: 11.8 MB, less than 37.40% of Python online submissions for Positions of Large Groups.
每日格言:常常是最终一把钥匙打开了门。
请作者吃饺子 支付宝