题目大意
题目连接:beautiful string
写代码之前,考虑清楚流程,以及需要维护的变量....
实现
#include<iostream> #include<stdio.h> #include<string.h> #include<stack> #include<vector> #include<unordered_set> #include<unordered_map> using namespace std; char str[10 * 1024 * 1024 + 2]; int main(){ int T; scanf("%d", &T); while (T--){ int n; scanf("%d", &n); getchar(); scanf("%s", str); int i = 0; bool valid = false; int beg = 0, end = 0; int count_1 = 0; //前2个字符连续的个数 int count_2 = 0; //前1个字符连续的个数 while (beg < n && !valid){ char cur = str[beg]; //当前字符 while (end < n && !valid){ if (str[end] == cur){ //如果前两个字符都有,且当前字符数目大于等于中间字符数目, //则肯定可以形成一个valid的子串 if (count_2 && count_1 && end - beg + 1 >= count_2){ valid = true; break; } end++; } else{ if (str[end] - cur != 1){//出现了一个不连续字符,则清空count_1,count_2 count_1 = 0; count_2 = 0; } else{ //当前字符之前的那个字符的连续个数大于count_2的个数, //则只能以当前字符作为新的中间字符 count_2,且 //count_1 清空 if (count_2 && count_2 < end - beg){ count_1 = 0; count_2 = end - beg; } else{ //更新count_1 为count_2 //更新 count_2为 end-beg; count_1 = count_2; count_2 = end - beg; } } break; } } beg = end; } if (valid) printf("YES\n"); else printf("NO\n"); } return 0; }
时间: 2024-10-19 05:37:23