返回信息流“aaabbcdeeee”,这种字符串,想要知道每组重复的字符的坐标,比如,aaa的坐标是0,2;bb的坐标是3,4;eeee的坐标是7,10。用java写有什么好的方法吗,循环少一些的
这是一条镜像帖。来源:北邮人论坛 / study-share / #202399同步于 2021/10/13
该镜像源已超过 30 天没有更新,可能在源站已被删除。
StudyShare机器人发帖
“aaabbcdeeee”,这种字符串,想要知道每组重复的字符的坐标,
alexljs2019
2021/10/13镜像同步8 回复
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
抛砖引玉来个 Python 3.9 的
```python
def f(s: str) -> list[tuple[int, int]]:
i, result = 0, []
for _, group in groupby(s):
len_group = len(list(group))
result.append((i, i + len_group)) # [lo, hi)
i += len_group
return result
def shorter_f(s: str) -> list[tuple[int, int]]:
# Really ugly one-liner of above
return reduce(lambda ans, g: ans + [(ans[-1][1], ans[-1][1] + len(list(g[1])))], groupby(s), [(0, 0)])[1:]
word = "aaabbcdeeee"
print(f(word))
print(shorter_f(word))
# [(0, 3), (3, 5), (5, 6), (6, 7), (7, 11)]
```
【 在 yo1995 的大作中提到: 】
: [md]
: 抛砖引玉来个 Python 3.9 的
: ```python
: ...................
谢谢
【 在 alexljs2019 的大作中提到: 】
: “aaabbcdeeee”,这种字符串,想要知道每组重复的字符的坐标,比如,aaa的坐标是0,2;bb的坐标是3,4;eeee的坐标是7,10。用java写有什么好的方法吗,循环少一些的
```python
reduce(lambda x, y: x + [ [y[0], (x[-1][1][1] + 1, y[1] + x[-1][1][1]) ] ], [(k, len(list(g))) for k, g in groupby('AAAABBBCCD')], [['^', (-1, -1)]])[1:]
'''
[['A', (0, 3)], ['B', (4, 6)], ['C', (7, 8)], ['D', (9, 9)]]
'''
```