字符串匹配

题目 字符串匹配

image-8065e45d

思路分析

把[]中间部分当成一个字符位进行比较

把[]中的东西提出来

用find进行匹配

代码实现

#include<bits/stdc++.h>

using namespace std;

const int N=1010;

string strs[N],p;

int n;

string to_lower(string s){

    string res;

    for(auto c:s)

        res+=tolower(c);

    return res;

}

bool match(string a,string b){

    //a串中没括号 每轮++即可 b串可能有括号 手动移动指针

    for(int i=0,j=0;i<a.size() || j<b.size();i++)

    {

        //如果一个走完了另一个没走完 肯定不匹配

        if(i==a.size() || j==b.size())

            return false;

        //如果没有括号 直接比对即可

        if(b[j]!='['){

            if(a[i]!=b[j])

                return false;

            j++;

        }

        //如果有括号 把括号里的东西提出来

        else{

            string s;

            j++;//把左括号[给去了

            while(b[j]!=']')

                s+=p[j++];

            j++;//右括号]去掉

            if(s.find(a[i])==-1)

                return false;

        }

    }

    return true;

}

int main()

{

    cin>>n;

    for(int i=0;i<n;i++){

        cin>>strs[i];

    }

    cin>>p;

    p=to_lower(p);

    for(int i=0;i<n;i++)

        if(match(to_lower(strs[i]),p))

            cout<<i+1<<" "<<strs[i]<<endl;

    return 0;

}

同类题型

视频讲解


⬅️ 子串匹配 🏠 00-刷题理模型 ➡️ 小牛快传