数据结构练习(线性结构)

数据结构练习(线性结构)

只能说这次c++挺偷懒的,我也挺偷懒的

6-1 模式匹配

int BF(string s, string t)
{
    return s.find(t);
}

函数,确实是函数

7-1 【模板】KMP字符串匹配

#include 
#include 
using namespace std;

int main()
{
    string text, pattern;
    cin >> text >> pattern;
    text.insert(0, " "), pattern.insert(0, " ");
    int n = pattern.size() - 1, m = text.size() - 1, next[n] = {0};

    for (int i = 2, j = 0; i <= n; i ++ )
    {
        while (j && pattern[i] != pattern[j + 1]) j = next[j];
        if (pattern[i] == pattern[j + 1]) j ++ ;
        next[i] = j;
    }
    
    for (int i = 1, j = 0; i <= m; i ++ )
    {
        while (j && text[i] != pattern[j + 1]) j = next[j];
        if (text[i] == pattern[j + 1]) j ++ ;
        if (j == n)
        {
            printf("%d\n", i - n + 1);
            j = next[j];
        }
    }

    for (int i = 1; i <= n; i++)
        cout << (i == 1 ? "" : " ") << next[i];

    return 0;
}

模板题唉

7-2 有序链表的归并

#include 
#include 
#include 
using namespace std;

int main()
{
    int m = 0, n = 0;
    while (cin >> m >> n)
    {
        int tmp = 0;
        vector<int>a;
        for (int i = 0; i < m + n; i++)
        {
            cin >> tmp;
            a.push_back(tmp);
        }
        sort(a.begin(), a.end());
        for (int i = 0; i < a.size(); i++)
        {
            cout << (i == 0 ? "" : " ") << a[i];
        }
        cout << endl;
    }
    return 0;
}

链表?不,数组排序

7-3 括弧匹配检验(check)

#include 
#include 
#include 
using namespace std;

int main()
{
    bool flag = true;
    string str;
    cin >> str;
    stack<char>a;

    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] == '[' || str[i] == '(')
        {
            a.push(str[i]);
        }
        else
        {
            if (a.empty()) 
            {
                flag = false;
                break;
            }
            else
            {
                if (str[i] == ']' && a.top() == '[' || str[i] == ')' && a.top() == '(')
                {
                    a.pop();
                }
                else
                {
                    flag = false;
                    break;
                }
            }
        }
    }
    if (!a.empty()) flag = false;

    if (flag) cout << "OK";
    else cout << "Wrong";

    return 0;
}

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