通过小哼的记录,请你求出小哈笑声的最大长度。
输入的第一行给出小哈说话的长度。
随后一行中输入一行长度为字符串
——表示小哈的话。
仅由小写字母组成。
输出小哈笑声的最大长度。
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);
}
}
#include <iostream>
using namespace std;
#include<string>
#include<algorithm>
int main() {
int N;
cin>>N;
int cur_len=0,max_len=0;
string s;
cin>>s;// 遍历 判断当前字符与前一个字符 判断是否延续了笑声
for(int i=0;i<s.size();i++){
if(s[i]=='a'){
if(i==0||cur_len==0){
cur_len++;
}
if(i!=0&&s[i-1]=='h'){
cur_len++;
}
if(i!=0&&s[i-1]!='h'){
max_len=max(cur_len,max_len);
cur_len=0;
}
}
if(s[i]=='h'){
if(i==0||cur_len==0){
cur_len++;
}
if(i!=0&&s[i-1]=='a'){
cur_len++;
}
if(i!=0&&s[i-1]!='a'){
max_len=max(cur_len,max_len);
cur_len=0;
}
}
}
max_len=max(cur_len,max_len);
cout<<max_len;
}
// 64 位输出请用 printf("%lld") 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();
}
}