9/9 每日一題(回傳連續出現3次以上的元素開字串中開始到結束的索引)
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.
Example 1:
Input: s = "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the only large group with start index 3 and end index 6.
Example 2:
Input: s = "abc" Output: [] Explanation: We have groups "a", "b", and "c", none of which are large groups.
Example 3:
Input: s = "abcdddeeeeaabbbcd" Output: [[3,5],[6,9],[12,14]] Explanation: The large groups are "ddd", "eeee", and "bbb".
Constraints:
1 <= s.length <= 1000scontains lowercase English letters only.
class Solution:
def largeGroupPositions(self, s: str) -> List[List[int]]:
s_dict=Counter(s)
large=[]
for k, v in s_dict.items():
if v>=3:
large.append(k)
n,c=0,0
res=[]
start,end=None,None
while n< len(s):
if c>0 and s[n] != s[n-1]:
#初始化
c=0
start,end=None,None
if s[n] in large:
c+=1 #開始計算是否超過三
if not start and start !=0: #檢查start是否存在,避免從0開始被洗掉
start=n
if c>=3 and n==len(s)-1:
res.append([start,n])
elif c>=3 and s[n+1] != s[n]:
end=n
res.append([start,end])
n+=1
return res
-----------------------------------
class Solution:
def largeGroupPositions(self, s: str) -> List[List[int]]:
ans = []
i = 0
while i < len(s):
char = s[i]
start = i
current = i
while current < len(s) and s[current] == char:
current += 1
if current - start >= 3:
ans.append([start, current-1])
i = current
return ans
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁