import java.util.Scanner; /** * @author supermejane * @date 2025/10/3 * @description 牛客算法学习篇-算法入门 BGN5穷哈哈~ */ public class Bgn5 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int len = in.nextInt(); in.nextLine(); String s = in.nextLine(); //解法一:直接单个指针遍历就行 int i = 0, result = Integer.MIN_VALUE, subLen = 0; while (i < len) { if (illegal(s, i)) { subLen++; } else { //非字串部分,直接结束字串 result = Math.max(subLen, result); subLen = s.charAt(i) == 'a' || s.charAt(i) == 'h' ? 1 : 0; } i++; } result = Math.max(result, subLen); System.out.println(result); } //字串部分 public static boolean illegal(String s, int i) { return (s.charAt(i) == 'a' && (i == 0 || s.charAt(i - 1) == 'h')) || (s.charAt(i) == 'h' && (i == 0 || s.charAt(i - 1) == 'a')); } //下面是解法二:双指针 public static int subLength(String s) { //p1->s, p2->sub字串 int p1 = 0, p2 = 0 , result = 0, subLen = 0; while (p1 < s.length()) { if (illegal2(s, p1)) { p2 = p1 + 1; subLen = 1; while (p2 < s.length() && ((s.charAt(p2) == 'a' && s.charAt(p2 - 1) == 'h') || (s.charAt(p2) == 'h' && s.charAt(p2 - 1) == 'a'))) { subLen++; p2++; } p1 = p2; result = Math.max(result, subLen); } else { p1++; } } return result; } //子串开始 public static boolean illegal2(String s, int i) { if (s.charAt(i) == 'a') { return i == 0 || s.charAt(i) != 'h'; } else if (s.charAt(i) == 'h') { return i == 0 || s.charAt(i) != 'a'; } return false; } }