import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner=new Scanner(System.in); int n=scanner.nextInt(); String string=scanner.next(); int count=0; int max=-1; int flag=-1; for (int i = 0; i < n-1; i++) { char c=string.charAt(i); if(c!='a'&&c!='h') { if(count>max)max=count; count=0; continue; } if(c=='a') { flag=1; if(string.charAt(i+1)=='h') { count++; }else { if(count>max)max=count; count=0; } }else if(c=='h') { flag=1; if(string.charAt(i+1)=='a') { count++; }else { if(count>max)max=count; count=0; } } } if(flag==1) { count++; max++; } if(max<count)max=count; System.out.println(max); } }
这一题我个人感觉是挺有难度的,它要计算aha这样最长连续的长度,我们该怎么做呢,首先,我设计了count来统计长度,但是只有在当前为a并且下一个为h,或者当前为h,下一个为a的情况下,count才会++,这样正常情况下是会少了开头那个a或h的,那么我等最后再给它加上。如果当前字符不为a或h,那么截止了,与max比较,并且count归0。同样的,如果a后面不是h,或者h后面不是a,我们也要把count清零,至于我为什么要设计一个flag,这是因为如果整个字符串中都没有a或者h,那么最后盲目加1,就是错误的,所以我设计了flag来判断该不该加1