通过小哼的记录,请你求出小哈笑声的最大长度。
输入的第一行给出小哈说话的长度。
随后一行中输入一行长度为字符串
——表示小哈的话。
仅由小写字母组成。
输出小哈笑声的最大长度。
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>
int main(){
int N;
string s;
cin >> N >> s;
int lenth = 0;
int lenth_max = 0;
char prv = 0;
for(const auto& c : s){
if(c != 'a' && c != 'h'){
lenth = 0;
prv = 0;
continue;
}
if(prv = 0 || c != prv){
lenth++;
prv = c;
if(lenth > lenth_max) lenth_max = lenth;
}
else{
lenth = 1;
prv = c;
}
}
cout << lenth_max << endl;
return 0;
} #include <iostream>
using namespace std;
int main() {
int N,m=0,l=0,sgl=-1;cin>>N;
string s;cin>>s;
for(int i=0;i<N;i++){
if(s[i]=='a'&&sgl==-1){
sgl=0;l++;
}else if(s[i]=='h'&&sgl==-1){
sgl=1;l++;
}else if(s[i]=='a'&&sgl==1){
sgl=0;l++;
}else if(s[i]=='h'&&sgl==0){
sgl=1;l++;
}else{
if(m<l) m=l;
if(s[i]=='a'&&sgl==0){
sgl=0;l=1;
}else if(s[i]=='h'&&sgl==1){
sgl=1;l=1;
}else l=0;
}
}
if(m<l) m=l;
cout<<m;
} #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")