华为在线机试算法题

华为在线机试算法题

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

1.题目描述

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

#include
#include
#include

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;
}

你可能感兴趣的:(求字符串中最长数字串,笔试或面试中的算法题)