通过小哼的记录,请你求出小哈笑声的最大长度。
输入的第一行给出小哈说话的长度。
随后一行中输入一行长度为字符串
——表示小哈的话。
仅由小写字母组成。
输出小哈笑声的最大长度。
7 abacaba
1
20 ahahahahahahahahahah
20
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = in.next();
in.close();
int maxLen = 0;
int currLen = 0;
char last = 0; // ASCII中0不是任何可见字符,相当于null
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
// 只处理a和h,其他字符直接重置
if (c != 'a' && c != 'h') {
currLen = 0;
last = 0;
continue;
}
// 当前是合法字符时的处理
if (last == 0) {
// 首次遇到合法字符,初始化序列
currLen = 1;
} else if (c != last) {
// 与上一个字符不同,延长序列
currLen++;
} else {
// 与上一个字符相同,重置为当前字符的新序列
currLen = 1;
}
// 更新上一个字符和最大长度,实时更新,这里很重要!
last = c;
if (currLen > maxLen) {
maxLen = currLen;
}
}
System.out.println(maxLen);
}
}
n = int(input()) s = input() s = s + 'g' l = [] count = 0 for i in range(len(s)): if count == 0: if s[i] == 'a'&nbs***bsp;s[i] == 'h': count += 1 else: if s[i] == 'a' and s[i-1] == 'h': count += 1 elif s[i] == 'h' and s[i-1] == 'a': count += 1 elif s[i] == 'a'&nbs***bsp;s[i] == 'h': l.append(count) count = 1 else: l.append(count) count = 0 if l == []: print(0) else: print(max(l))
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int N = in.nextInt();
in.nextLine();
String str = in.nextLine();
ArrayList<Integer> list = new ArrayList<>();
int numA = 0, numH = 0;
// 统计'a'和'h'的数量
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == 'a') numA++;
else if (c == 'h') numH++;
}
if(numA == 0 && numH == 0){
System.out.println("0");
continue;
}
// 处理只有一种字符的情况
if ((numA == 0 && numH != 0) || (numH == 0 && numA != 0)) {
System.out.println("1");
continue;
}
// 统计交替序列的最大长度
int currentLength = 1;
for (int i = 1; i < str.length(); i++) {
char prev = str.charAt(i - 1);
char curr = str.charAt(i);
if ((prev == 'a' && curr == 'h') || (prev == 'h' && curr == 'a')) {
currentLength++;
} else {
list.add(currentLength);
currentLength = 1;
}
}
list.add(currentLength); // 添加最后一个序列的长度
// 输出最大长度
if (list.isEmpty()) {
System.out.println("0");
} else {
int max = list.get(0);
for (int len : list) {
if (len > max) max = len;
}
System.out.println(max);
}
}
in.close();
}
}