top1编程
← 返回题目
题解

【基础】小X数字母

2 条题解

  • 0
    @ 2026-10-24 5:12:38

    1. 解题思路

    顺序扫描字符串,用s记录当前位置结尾的连续A长度,ans记录扫描过的最大连续长度。遇到A就增加s并更新ans,遇到其他字符就把s清零。

    2. 坑点和注意事项

    只清零当前连续长度,历史最大值不能清零。在遇到A时立即更新答案,因此开头、末尾和整个字符串都是A的情况都能处理;没有A时输出0。N≤100000,长度计数用int足够。

    3. 复杂度

    • 时间复杂度:O(n),每个字符只扫描一次。
    • 空间复杂度:O(n),string保存输入字符串;计数变量只需O(1)。
    /*
    思路:顺序扫描字符串,记录当前连续A的长度,并维护历史最大值。
    关键:遇到非A字符时当前长度清零,但历史答案保留。
    坑点:开头或末尾的一段A都要计算,没有A时输出0。
    时间复杂度:O(n)。
    空间复杂度:O(n);n最多100000,长度计数使用int。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        int n, s = 0, ans = 0;
        string a;
        cin >> n >> a;
        for (int i = 0; i < n; i++)
        {
            if (a[i] == 'A')
            {
                s++;
                ans = max(ans, s);
            }
            else
            {
                // 连续段在非A字符处结束,后面需要重新计数。
                s = 0;
            }
        }
        cout << ans << endl;
        return 0;
    }
    
    • 0
      @ 2026-7-29 0:15:33
      #include <iostream>
      #include <string>
      using namespace std;
      
      int main() {
          int N;
          string s;
          cin >> N >> s;
          
          int max_count = 0;
          int current_count = 0;
          
          for (char c : s) {
              if (c == 'A') {
                  current_count++;
                  if (current_count > max_count) {
                      max_count = current_count;
                  }
              } else {
                  current_count = 0;
              }
          }
          
          cout << max_count << endl;
          return 0;
      }
      
      • 1