字符串匹配——Sunday算法

求第一个串 :

#include <iostream>
#include <string>

using namespace std;

const int maxNum = 1005;

int shift[maxNum];
int Sunday(const string& T, const string& P) {
    int n = T.length();
    int m = P.length();

    // 默认值,移动m+1位
    for(int i = 0; i < maxNum; i++) {
        shift[i] = m + 1;
    }

    // 模式串P中每个字母出现的最后的下标
    // 所对应的主串参与匹配的最末位字符的下一位字符移动到该位,所需要的移动位数
    for(int i = 0; i < m; i++) {
        shift[P[i]] = m - i;
    }

    // 模式串开始位置在主串的哪里
    int s = 0;
    // 模式串已经匹配到的位置
    int j;
    while(s <= n - m) {
        j = 0;
        while(T[s + j] == P[j]) {
            j++;
            // 匹配成功
            if(j >= m) {
                return s;
            }
        }
        // 找到主串中当前跟模式串匹配的最末字符的下一个字符
        // 在模式串中出现最后的位置
        // 所需要从(模式串末尾+1)移动到该位置的步数
        s += shift[T[s + m]];
    }
    return -1;
}



/**
IN
at the thought of
though

OUT
7
**/
int main() {
    // 主串和模式串
    string T, P;
    while(true) {
        // 获取一行
        getline(cin, T);
        getline(cin, P);
        int res = Sunday(T, P);
        if(res == -1) {
            cout << "主串和模式串不匹配。" << endl;
        } else {
            cout << "模式串在主串的位置为:" << res << endl;
        }
    }
    return 0;
}

求n个串的位置:

#include <iostream>
#include <string>
using namespace std;
const int maxNum = 1005;
int shift[maxNum];
int ans[1000];
int cnt = 0;
void Sunday(const string& T, const string& P) {
	int n = T.length();
	int m = P.length();
	for (int i = 0; i < maxNum; i++) {
		shift[i] = m + 1;
	}
	for (int i = 0; i < m; i++) {
		shift[P[i]] = m - i;
	}
	int s = 0;
	int j;
	while (s <= n - m) {
		j = 0;
		while (T[s + j] == P[j]) {
			j++;
			// 匹配成功
			if (j == m) {
				j = 0;
				ans[cnt++] = s;
				break;
			}
		}
		s += shift[T[s + m]];
	}
}

int main() {
	// 主串和模式串
	string T, P;
	while (true) {
		// 获取一行
		getline(cin, T);
		getline(cin, P);
		Sunday(T, P);
		if (cnt==0) {
			cout << "主串和模式串不匹配。" << endl;
		}
		else {
			for (int i = 0; i < cnt; i++)
			{
				cout << "模式串在主串的位置为:" << ans[i] << endl;
			}
			memset(ans, 0, sizeof(ans));
			cnt = 0;
		}
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值