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

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

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

6-1 模式匹配

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

函数,确实是函数

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

#include <iostream>
#include <string>
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 <iostream>
#include <algorithm>
#include <vector>
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 <iostream>
#include <string>
#include <stack>
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值