830. Positions of Large Groups@python
2024-10-20 11:48:45
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
最新文章
- Docker学习---ubuntu环境
- SQLServer idenity 字段跳值
- Groovy 处理 XML
- java基础,继承类题目:编写一个Java应用程序,该程序包括3个类:Monkey类、People类和主类 E
- 百度编辑器修改,不让它自动替换html标签
- PHP : Reflection API
- 自动装配Bean
- KTHREAD 线程调度 SDT TEB SEH shellcode中DLL模块机制动态获取 《寒江独钓》内核学习笔记(5)
- nova分析(2)—— nova-all
- mr的logs的查看
- [AngularJS] Accessible Button Events
- 关于Django模板渲染一个很重要的用途
- 关于埃博拉(Ebola)基础研究病毒
- winPcap编程之获取适配器信息(二)
- Linux chgrp命令
- haproxy使用演示--技术流ken
- 怎么让微信下载APK文件包,微信内置浏览器无法打开APP下载链接的解决方案
- hdu 3530 ";Subsequence"; (单调队列)
- bash编程-正则表达式
- IntelliJ IDEA 2017版 spring-boot2.0.2 自动配置Condition
热门文章
- jzoj5983. 【北大2019冬令营模拟2019.1.1】多边形 (组合数学)
- 怎么解决UIScrollView把uitableviewcell的点击事件屏蔽了
- Django (六) 视图 views
- Technocup 2017 - Elimination Round 1 (Unofficially Open for Everyone, Rated for Div. 2) B
- B. Dispersed parentheses 记忆化搜索 + 括号序列的状压表示
- 20 个案例教你在 Java 8 中如何处理日期和时间?
- spring security 5 There is no PasswordEncoder mapped for the id ";null"; 错误
- React项目搭建基于Karma的CI环境
- 事件冒泡之cancelBubble和stoppropagation的区别
- Vue-router 的练习