刷题:华为机试 HJ32 字符串运用-密码截取

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

int main()
{
    string s;
    vector<char> s2;
    while (cin >> s)
    {
        //去除字母和数字以外的其他字符
        for (int i = 0; i < s.length(); i++)
        {
            if ((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z'))
            {
                s2.push_back(s[i]);
            }
        }

        //找出所有的对称子串,并对所有子串的长度进行存储
        int res = 1;
        vector<int> save;
        for (int i = 0; i < s2.size(); i++)
        {
            int l = i - 1;
            int r = i + 1;
            while (l >= 0 && r < s.length() && s2[l] == s2[r])
            {
                int len = r - l + 1;
                if (len > res)
                {
                    res = len;
                }
                l--;
                r++;
            }
            save.push_back(res);

            l = i;
            r = i + 1;
            while (l >= 0 && r < s.length() && s2[l] == s2[r])
            {
                int len = r - l + 1;
                if (len > res)
                {
                    res = len;
                }
                l--;
                r++;
            }      
            save.push_back(res);
        }

        sort(save.begin(), save.end());
        //用来判断输入字符串中,无回文子串(回文子串长度为1)
        int count = 0;
        for (int i = 0; i < save.size(); i++)
        {
            if (save[i] == 1)
                count++;
        }

        for (int i = save.size() - 1; i >= 0; i--)
        {
            if (save.size() == count) //说明save中全是1,则回文子串长度为1。
            {
                cout << '1' << endl;
                break;
            }
            else if (i == save.size() - 1) //sort排序后,只用输出最大的数字,最大数字排在最后一位。
            {
                cout << save[i] << endl;
                break;
            }
        }
        save.clear(); //切记清空save中的元素
        s2.clear();
    }

    return 0;
}

注意:
多组输入时,使用vector时,记得使用clear函数,清空对应vector中存储的每一组的数据,这点很重要!

在这里插入图片描述
华为机试被鸽了。害!还继续做题吗?

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值