2016/10/20 1002. 字符串匹配

本质上就是一个KMP算法的题目,核心就是算出next数组,之后的匹配就简单了。next的算法是在书上找到的。(到处都有)

#include <iostream>
#include <string>
using namespace std;
int main()
{
	int n;
	while (cin >> n)
	{
		int* code = new int[n];
		for (int i = 0; i <= n - 1; i++)
		{
			cin >> code[i];
		}
		int m;
		cin >> m;
		int* door = new int[m];
		for (int i = 0; i <= m - 1; i++)
		{
			cin >> door[i];
		}
		//KMP NEXT
		int *next = new int[n];
		int k = 0;
		next[0] = 0;
		for (int i = 1; i <= n - 1; i++)
		{
			while ((k > 0) && (code[k] != code[i]))
			{
				k = next[k];
			}
			if (code[k] == code[i])
			{
				k++;
			}
			next[i] = k;
		}
		//MATCH
		int match = 0;
		bool succeed = false;
		for (int i = 0; i <= m - 1; i++)
		{
			while (match > 0 && code[match] != door[i])
			{
				match = next[match];
			}
			if (code[match] == door[i])
			{
				match++;
			}
			if (match == n)
			{
				cout << i - match + 1 << endl;
				succeed = true;
				break;
			}
		}
		if(!succeed)
		cout << "no solution" << endl;
	}
}

LeetCode上的一道题也是类似的,代码放在一起了,上面的代码似乎有些错误,以下面的为准吧:

class Solution {
public:
    vector<int> Calnext(string s)
    {
        int n = s.length();
        vector<int> ans(n);
        ans[0] = 0;
        int k = 0;
        for(int i=1;i<n;i++)
        {
            while(k > 0 && s[k] != s[i])
            {
                k = ans[k - 1];
            }
            if(s[k] == s[i])
            {
                k++;
            }
            ans[i] = k ;
        }
        return ans;
    }
    int strStr(string haystack, string needle) {
        int m = haystack.length(), n = needle.length();
        if(n==0)return 0;
        else if(m==0) return -1;
        vector<int> next = Calnext(needle);
        int match = 0;
        for(int i =0;i<m;i++)
        {
            while(match > 0 && haystack[i] != needle[match])
            {
                match = next[match-1];
            }
            if(haystack[i] == needle[match])
            {
                match++;
            }
            if(match == n)
            {
                return i - match  + 1;
            }
        }
        return -1;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值