求出字符串内所有对称子字符串

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

    vector<string> getSubString(string str)
    {
    vector<string> allsubstr;
    if (str.size() < 1)
    {
    return allsubstr;
    }

    // bcb bccb
    char* p_str = (char*)str.c_str();
    char* ptr = p_str;
    char* pre = p_str;
    char* next = p_str;
    int index = 0;
    int index2 = 0;

    while (*ptr != ‘\0’)
    {
    pre = ptr – 1;
    next = ptr + 1;
    index2 = 0;

    //bcb
    while (pre >= p_str && *next != ‘\0’ && *pre == *next)
    {
    //左指针不能小于首地址,右指针不能到达结束符,并且左右字符相等
    pre–;
    next++;
    index2++; //确定位移了几位

    }

    //当前字符左右检测完成
    if (index2 >= 1 && index – index2 >= 0)
    {
    int min = index – index2;
    int max = index + index2;
    string temp = str.substr(min, max – min + 1);//截取min – max之间的字符串
    allsubstr.push_back(temp);
    }

    //bccb
    pre = ptr;
    next = ptr + 1;
    index2 = 0;

    while (pre >= p_str && *next != ‘\0’ && *pre == *next)
    {
    pre–;
    next++;
    index2++;
    }
    //当前字符左右检测完成
    if (index2 >= 1 && index – index2 + 1 >= 0)
    {
    int min = index – index2 + 1;
    int max = index + index2;
    string temp = str.substr(min, max – min + 1);//截取min – max之间的字符串
    allsubstr.push_back(temp);
    }

    index++; //当前检测字符下标
    ++ptr;//下一个字符
    }
    return allsubstr;
    }

    int main()
    {
    string in;
    cin >> in;
    vector<string> ret = getSubString(in);
    for (int i = 0; i < ret.size(); i++)
    {
    cout << ret.at(i) << endl;
    }
    system(“PAUSE”);
    return 0;
    }

    有帮助就分享一下吧!

    转载请注明:少狼 – 敬畏知识的顽皮狗 » 求出字符串内所有对称子字符串

    喜欢 1

*

还没有人抢沙发呢~