OR54 字符串中找出连续最长的数字串

目录

一、题目

二、解答

(一)问题一:在记录完一组连续字符串后,没有注意判别紧随其后的非数字字符

(二)问题二:越界访问

(三)正确


一、题目

字符串中找出连续最长的数字串_牛客题霸_牛客网

OR54 字符串中找出连续最长的数字串_第1张图片

二、解答

(一)问题一:在记录完一组连续字符串后,没有注意判别紧随其后的非数字字符

OR54 字符串中找出连续最长的数字串_第2张图片 

#include 
#include 
#include 
using namespace std;
 
#include 
#include 
#include 
using namespace std;
 
int main() {
    string s;
    cin >> s;
    int prev = 0, next = 0;
    string s2;
    bool isfirst = false;
    while (next < s.length()) {
        if (s[next] <= '9' && s[next] >= '0') {
            if (isfirst == false) {
                prev = next;
                isfirst = true;
            }
            ++next;
        } else {
            isfirst = false;
            if (next - prev > s2.length()) {
                s2 = s.substr(prev, next - prev);
            }
            ++next;
        }
    }
 
 
    if (next - prev > s2.length()) {
        s2 = s.substr(prev, next - prev);
    }
 
    cout << s2;
    return 0;
 
}

(二)问题二:越界访问

OR54 字符串中找出连续最长的数字串_第3张图片

#include 
#include 
#include 
using namespace std;

int main() {
    string s;
    cin >> s;
    int prev = 0, next = 0;
    string s2;
    bool isfirst = false;
    while (next < s.length()) {
        if (s[next] <= '9' && s[next] >= '0')
        {
            if (isfirst == false)
            {
                prev = next;
                isfirst = true;
            }
            ++next;
        }
        else
        {
            isfirst = false;
            if (s[next - 1] <= '9' && s[next - 1] >= '0')
            {
                if (next - prev > s2.length())
                {
                    s2 = s.substr(prev, next - prev);
                }
            }

            ++next;
        }
    }

    if (s[next - 1] <= '9' && s[next - 1] >= '0')
    {
        if (next - prev > s2.length()) //注意最后一个数字串
        {
            s2 = s.substr(prev, next - prev);
        }
    }


    cout << s2;
    return 0;

}

(三)正确

OR54 字符串中找出连续最长的数字串_第4张图片

#include 
#include 
#include 
using namespace std;

int main() {
    string s;
    cin >> s;
    int prev = 0, next = 0;
    string s2;
    bool isfirst = false;//判断prev是不是第一次出现
    while (next < s.length()) {
        if (s[next] <= '9' && s[next] >= '0')
        {
            if (isfirst == false)
            {
                prev = next;
                isfirst = true;
            }
            ++next;
        }
        else
        {
            isfirst = false;
            if (s[prev] <= '9' && s[prev] >= '0' && s[next - 1] <= '9' && s[next - 1] >= '0')
            {
                if (next - prev > s2.length())
                {
                    s2 = s.substr(prev, next - prev);
                }
            }

            ++next;
        }
    }

    if (s[next - 1] <= '9' && s[next - 1] >= '0')//注意跳出循环后的最后一个数字串
    {
        if (next - prev > s2.length()) 
        {
            s2 = s.substr(prev, next - prev);
        }
    }


    cout << s2;
    return 0;

}

 

你可能感兴趣的:(牛客/力扣,c++,算法,数据结构)