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:

Input: "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]

原题地址: Positions of Large Groups

题意: 将数组分组,标记每一组的首尾索引值,返回分组长度等于3的索引值

难度: Easy

思路:

(1)遍历数组并用count数组标记,注意首尾边界

(2)遍历count,找出长度大于等于3的分组

代码:

class Solution(object):
def largeGroupPositions(self, S):
"""
:type S: str
:rtype: List[List[int]]
"""
count = []
i = 0
j = 1 while j <= len(S):
if j == len(S):
count.append([i, j-1])
break if S[i] == S[j]:
j += 1
else:
count.append([i, j-1])
i = j res = []
for c in count:
if c[1] - c[0] + 1 >= 3:
res.append(c)
return res

时间复杂度: O(n)

空间复杂度: O(n)

在上面的基础上优化一下,一次变量即可

代码:

class Solution(object):
def largeGroupPositions(self, S):
"""
:type S: str
:rtype: List[List[int]]
"""
res = []
i, j = 0, 1
n = len(S)
while j < n:
if S[j] != S[j-1]: # 找到不相等的值
count = j - i
if count >= 3:
res.append([i, j-1])
i = j
j += 1 if j - i >= 3: # 处理边界问题
res.append([i, j-1]) return res

最新文章

  1. Docker学习---ubuntu环境
  2. SQLServer idenity 字段跳值
  3. Groovy 处理 XML
  4. java基础,继承类题目:编写一个Java应用程序,该程序包括3个类:Monkey类、People类和主类 E
  5. 百度编辑器修改,不让它自动替换html标签
  6. PHP : Reflection API
  7. 自动装配Bean
  8. KTHREAD 线程调度 SDT TEB SEH shellcode中DLL模块机制动态获取 《寒江独钓》内核学习笔记(5)
  9. nova分析(2)—— nova-all
  10. mr的logs的查看
  11. [AngularJS] Accessible Button Events
  12. 关于Django模板渲染一个很重要的用途
  13. 关于埃博拉(Ebola)基础研究病毒
  14. winPcap编程之获取适配器信息(二)
  15. Linux chgrp命令
  16. haproxy使用演示--技术流ken
  17. 怎么让微信下载APK文件包,微信内置浏览器无法打开APP下载链接的解决方案
  18. hdu 3530 &quot;Subsequence&quot; (单调队列)
  19. bash编程-正则表达式
  20. IntelliJ IDEA 2017版 spring-boot2.0.2 自动配置Condition

热门文章

  1. jzoj5983. 【北大2019冬令营模拟2019.1.1】多边形 (组合数学)
  2. 怎么解决UIScrollView把uitableviewcell的点击事件屏蔽了
  3. Django (六) 视图 views
  4. Technocup 2017 - Elimination Round 1 (Unofficially Open for Everyone, Rated for Div. 2) B
  5. B. Dispersed parentheses 记忆化搜索 + 括号序列的状压表示
  6. 20 个案例教你在 Java 8 中如何处理日期和时间?
  7. spring security 5 There is no PasswordEncoder mapped for the id &quot;null&quot; 错误
  8. React项目搭建基于Karma的CI环境
  9. 事件冒泡之cancelBubble和stoppropagation的区别
  10. Vue-router 的练习