25. 求满足条件的最长子串的长度

58 阅读1分钟

题目描述

给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度,字符串本身是其最长的子串,子串要求:

1、 只包含1个字母(az, AZ),其余必须是数字;

2、 字母可以在子串中的任意位置;

如果找不到满足要求的子串,如全是字母或全是数字,则返回-1。

输入描述

字符串(只包含字母和数字)

输出描述

子串的长度

用例

输入abC124ACb
输出4
说明满足条件的最长子串是C124或者124A,长度都是4
输入a5
输出2
说明字符串自身就是满足条件的子串,长度为2
输入aBB9
输出2
说明满足条件的子串为B9,长度为2
输入abcdef
输出-1
说明没有满足要求的子串,返回-1

思路:

滑动窗口

#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
using namespace std;

int main()
{
    string str;
    cin >> str;
    int left = 0, right = 0;
    int maxLen = -1;
    deque<int> deq; // 存储字母的位置
    bool hasLetter = false;
    for (right = 0; right < str.size(); right++)
    {
        if (isalpha(str[right])) {
            hasLetter = true;
            deq.push_back(right);

            while (deq.size() > 1) {
                left = deq.front() + 1;
                deq.pop_front();
            }
            if (left == right) {
                continue; // 只有一个字母不需要比较
            }
        }
        maxLen = max(maxLen, right - left + 1);
    }

    if (!hasLetter) {
        cout << -1 << endl;
        return 0;
    }
    cout << maxLen << endl;
    return 0;
}

2

#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
using namespace std;

int main()
{
    string str;
    cin >> str;
    int left = 0, right = 0;
    int maxLen = -1;
    deque<char> deq;
    int count = 0;// 存储字母的个数
    for (right = 0; right < str.size(); right++)
    {
        deq.push_back(str[right]);
        if (isalpha(str[right])) {
            count++;
        }
        while (count > 1) {
            if (isalpha(deq.front())) {
                count--;
            }
            deq.pop_front();
        }
    // 关键在于满足条件才进行比较
        if (count == 1 && deq.size() > 1) {
            maxLen = max(maxLen, (int)deq.size());
        }
    }

    cout << maxLen << endl;
    return 0;
}