如果一个01串任意两个相邻位置的字符都是不一样的,我们就叫这个01串为交错01串。例如: "1","10101","0101010"都是交错01串。
小易现在有一个01串s,小易想找出一个最长的连续子串,并且这个子串是一个交错01串。小易需要你帮帮忙求出最长的这样的子串的长度是多少。
输入包括字符串s,s的长度length(1 ≤ length ≤ 50),字符串中只包含'0'和'1'
输出一个整数,表示最长的满足要求的子串长度。
111101111
3
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.next(); int[] arr = new int[s.length()]; arr[0] = 1; int result = 1; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == s.charAt(i-1)) { arr[i] = 1; } else { arr[i] = arr[i-1] + 1; } result = Math.max(arr[i], result); } System.out.println(result); scanner.close(); } }
使用TMP记录循环中上一次的值跟后一次进行比对 不一样就计数
#coding=utf-8while1:s=raw_input()res=[]count=0fori inrange(len(s)):ifi==0:tmp=s[i]passelifs[i]!=tmp:count+=1tmp=s[i]passelifs[i]==tmp:res.append(count)count=0tmp=s[i]ifcount==len(s)-1:print(count)+1breakifnotres:print(0)breakprintmax(res)+1break