如果一个01串任意两个相邻位置的字符都是不一样的,我们就叫这个01串为交错01串。例如: "1","10101","0101010"都是交错01串。
小易现在有一个01串s,小易想找出一个最长的连续子串,并且这个子串是一个交错01串。小易需要你帮帮忙求出最长的这样的子串的长度是多少。
输入包括字符串s,s的长度length(1 ≤ length ≤ 50),字符串中只包含'0'和'1'
输出一个整数,表示最长的满足要求的子串长度。
111101111
3
s = list(input()) lenth = 1 a = [] a.append(lenth) for i in range(len(s)-1): if s[i] != s[i+1]: lenth += 1 if i + 2 >= len(s) - 1: continue if s[i+1] == s[i+2]: a.append(lenth) lenth = 1 a.append(lenth) print(max(a))
# 交错10串: python3 def fun(sr): # it only has one 1 or 0 length=0 length_old=0 if len(set(sr))==1: length=0 # it only has one num if len(sr)==1: length= 0 for i in range(len(sr)-1): if sr[i]+sr[i+1]==1: length_old += 1 # if we have a newly larger sequence, we update the length if length_old >= length: length = length_old else: # once we encounter a new sequence, we set again length to zero length_old=0 return (length + 1) if __name__=='__main__': s=[int(t) for t in list(input())] print(fun(s))
##python 版本 ##思路:检测数组前后的数值是否相等,不相等则加1,若相等则清0,重新开始计数, #直到遍历完全部数组的数 import sys line=sys.stdin.readline().strip() import sys line=sys.stdin.readline().strip() def get_longest_str(s): len_s=len(s) sample_len=1 max_len=1 for i in range(len_s-1): if s[i+1]!=s[i]: sample_len=sample_len+1 else: if sample_len>max_len: max_len=sample_len sample_len=1 if sample_len>max_len: max_len=sample_len return max_len print get_longest_str(line)