1
llbbzh 2015-11-01 11:53:03 +08:00
滑动窗口啊。
设序列为 a ,指定两个指针 h ( head ), t ( tail ),规定区间[h,t]中的数字必须全部为某个值,设为 v 为了让[h,t]中的数字全为 v ,显然初始时 h==t==1 如果 a[t+1]==v ,那么 t++ 如果 a[t+1]!=v ,那么输出 h 和 t ,并令 v=a[t+1],h=t=t+1 时间复杂度 O(n) |
2
Magic347 2015-11-01 12:05:34 +08:00
def find(s):
ret = [] if s is None or len(s) == 0: return ret start = 0 curr = s[0] for i in range(0, len(s)): if s[i] != curr: ret.append((start+1, i)) start = i curr = s[i] if i == len(s) - 1: ret.append((start+1, len(s))) else: if i == len(s) - 1: ret.append((start+1, len(s))) return ret 算法上没有特别之处,只是处理一些边界 case 时要细致一些,提供一些测试用例 find("") find("10") (1, 1) (2, 2) find("1111") (1, 4) find("1") (1, 1) find("11111111000001111101111100000001111") (1, 8) (9, 13) (14, 18) (19, 19) (20, 24) (25, 31) (32, 35) |
3
Magic347 2015-11-01 12:21:38 +08:00
这个回帖过滤代码缩进真是闹心啊,站主是不是可以考虑加一个代码缩进和高亮啊?
def find(s): ____ret = [] ____if s is None or len(s) == 0: ________return ret ____start = 0 ____curr = s[0] ____for i in range(0, len(s)): ________if s[i] != curr: ____________ret.append((start+1, i)) ____________start = i ____________curr = s[i] ____________if i == len(s) - 1: ________________ret.append((start+1, len(s))) ________else: ____________if i == len(s) - 1: ________________ret.append((start+1, len(s))) ____return ret |
4
meteor2013 OP @Magic347 谢谢哥们啊,太贴心了
话说代码缩进和高亮真的很有需要 |
5
Slienc7 2015-11-01 13:56:10 +08:00
|
6
menc 2015-11-02 01:09:36 +08:00
https://gist.github.com/PengFoo/51c0428fb67447abaf6a
print find("10") print find("1111") print find("1") print find("11111111000001111101111100000001111") 结果分别为: [(1, 1), (2, 2)] [(1, 4)] [(1, 1)] [(1, 8), (9, 13), (14, 18), (19, 19), (20, 24), (25, 31), (32, 35)] |