【编程题】求字符串中最长连续子串

【编程题】自字符串中最长连续子串

1、我的代码

#include 
#include <string>
using namespace std;
/*
void func(const string& str, string& res) {
    int curIndex = 0;
    int maxIndex = 0;
    res.clear();
    if(str.empty()) return;

    int curlen = 1;
    int maxlen = 1;

    for(int i = 0;i < str.size();i++) {
        if(i + 1 >= str.size()) break;
        if(str[i+1] - str[i] == 1) {
            curlen++;
            if(curlen > maxlen) {
                maxlen = curlen;
                maxIndex = curIndex;
            }            
        }
        else {
            curIndex = i+1;
            curlen = 1;
        }
    } 
    string tmp(str.begin()+maxIndex, str.begin()+maxIndex+maxlen);
    res.swap(tmp);
}
*/

void func(const string& str, string& res) {
    res.clear();
    if(str.empty()) return;
    int max1 = 0, max2 = 0;
    int cur1 = 0, cur2 = 0;

    for(int i = 1;i < str.size();i++) {
        if(str[i] - str[i-1] == 1) {
            cur2 = i;
            if(max2 - max1 < cur2 - cur1) {
                max1 = cur1;
                max2 = cur2;
            }
        }
        else {
            cur1 = cur2 = i;
        }
    }

    string tmp(str.begin()+max1, str.begin()+max2);
    tmp.swap(res);
}

int main() {
    string str = "jfabcdefghijkhsldk6789";
    string res;
    func(str, res);

    cout << res << endl;

    return 0;

}

2、我的代码(2018年8月14日)

#include 
#include 
using namespace std;

int main() {
    string str;
    cin >> str;
    int cur1 = 0, cur2 = 0, max1 = 0, max2 = 0;
    for(int i = 1;i < str.size();i++) {
        if(str[i] - str[i-1] == 1) {
            cur2 = i;
            if(max2-max1 < cur2-cur1) {
                max2 = cur2;
                max1 = cur1;
            }
        }
        else {
            cur1 = cur2 = i;
        }
    }
    string res(str.begin()+max1, str.begin()+max2+1);
    cout << res << endl;

    return 0;
}

你可能感兴趣的:(数据结构与算法)