华为在线机试算法题

华为在线机试算法题

整个考试共3道题目,可惜只会做第一道。。。感觉自己永远是菜鸟长不大了。。。

1.题目描述

给定一个字符串,输出字符串中最长的数字串,并把这个字符串的长度输出。请在一个字符串中找出连续最长的数字串,并把这个串的长度返回;如果存在长度相同的连续字符串,返回最后一个连续数字串。注意:数字串只需要是数字组成的就可以,并不要求顺序,比如数字串“1234”的长度就小于“1359055”,如果没有数字,则返回空字符串(“”)而不是NULL!
当时怎么写的已经忘了,在重写一遍。。
有问题,明儿再改改~

#include<iostream>
#include<string>
#include<vector>

using namespace std;

int main() {
    string str;
    getline(cin, str);//注意字符串中不要包含中文符号。。否则代码直接JJ
    if (str.size() == 0)
        cout << "" << ',' << 0 << endl;
    else {
        int len = str.size(), max=0, temp_begin = 0, temp_end = 0;
        vector<string> result;
        while (temp_end < len) {
            if (str[temp_end] < '0' || str[temp_end] > '9') { //字符非数字
                temp_end++;
                temp_begin++;
            }
            else { //字符是数字
                if (temp_end == 0 || (str[temp_end - 1] < '0' || str[temp_end - 1] > '9')) {
                    temp_begin = temp_end;
                    temp_end++;
                }
                else if (temp_end + 1 < len && (str[temp_end + 1] >= '0' && str[temp_end + 1] <= '9')) {
                    temp_end++;
                }
                else if (temp_end + 1 == len || (str[temp_end + 1] < '0' || str[temp_end + 1] > '9')) {
                    string temp_str;
                    for (int i = temp_begin; i <= temp_end; i++) 
                        temp_str += str[i];
                        result.push_back(temp_str);
                        temp_end++;
                        temp_begin = temp_end;
                }
            }
        }
        //输出
        for (int i = 0; i < result.size(); i++) {
            if (result[i] >= result[max])
                max = i;
        }
        cout << result[max] << ',' << result[max].size() << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值