蓝桥杯 字符串匹配 C++算法提高 HERODING的蓝桥杯之路

资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
  给出一个字符串和多行文字,在这些文字中找到字符串出现的那些行。你的程序还需支持大小写敏感选项:当选项打开时,表示同一个字母的大写和小写看作不同的字符;当选项关闭时,表示同一个字母的大写和小写看作相同的字符。
输入格式
  输入的第一行包含一个字符串S,由大小写英文字母组成。
  第二行包含一个数字,表示大小写敏感的选项,当数字为0时表示大小写不敏感,当数字为1时表示大小写敏感。
  第三行包含一个整数n,表示给出的文字的行数。
  接下来n行,每行包含一个字符串,字符串由大小写英文字母组成,不含空格和其他字符。
输出格式
  输出多行,每行包含一个字符串,按出现的顺序依次给出那些包含了字符串S的行。
样例输入
Hello
1
5
HelloWorld
HiHiHelloHiHi
GrepIsAGreatTool
HELLO
HELLOisNOTHello
样例输出
HelloWorld
HiHiHelloHiHi
HELLOisNOTHello
样例说明
  在上面的样例中,第四个字符串虽然也是Hello,但是大小写不正确。如果将输入的第二行改为0,则第四个字符串应该输出。
评测用例规模与约定
  1<=n<=100,每个字符串的长度不超过100。
  
解题思路:
看到这道题目的时候,我便想到了KMP算法,KMP算法是一种快速的字符串匹配算法,感兴趣的同学们可以从网上查阅相关资料,这里我就不多加赘述了。至于判断是否区分大小写,这里我采取了将字符串大小写转换的形式,如果是不区分大小写,那么把字符串全部转换成小写判断,如果是则不转换,如果转换也要保存初始值,以便输出。代码如下:

// KMP算法.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <bits/stdc++.h>
using namespace std;

int judge;

//构建前缀表
void prefix_table(string pattern, int prefix[], int n)
{
	int len = 0, i = 1;
	prefix[0] = 0;
	while (i < n)
	{
		if (pattern[i] == pattern[len])
		{
			len++;
			prefix[i] = len;
			i++;
		}
		else
		{
			if (len > 0)
			{
				len = prefix[len - 1];
			}
			else
			{
				prefix[i] = len;//len=0
				i++;
			}
		}
	}
}
//前缀表向后移动一位,第一位为-1
void move_prefix_table(int prefix[], int n)
{
	int i;
	for (i = n - 1; i > 0; i--)
		prefix[i] = prefix[i - 1];
	prefix[0] = -1;
}
//KMP算法的实现
void kmp_search(string text, string pattern)
{
	string res = text;
	if(judge == 0){
		transform(text.begin(),text.end(),text.begin(),::tolower);
		transform(pattern.begin(),pattern.end(),pattern.begin(),::tolower);
	}
	int n = pattern.length();
	int *prefix = (int *)malloc(sizeof(int)*n);
	prefix_table(pattern, prefix, n);
	move_prefix_table(prefix, n);
	int i = 0, j = 0;
	int tlen = text.length();
	int plen = pattern.length();
	while (i < tlen)
	{
		if ((j == (n - 1)) && (text[i] == pattern[j]))
		{
			//cout << (i - j + 1) << "  ";
			//找到一个后继续向后查找
			cout << res << endl;
			break;
		}
		if (text[i] == pattern[j])
		{
			i++;
			j++;
		}
		else
		{
			j = prefix[j];
			if (j == -1)
			{
				i++;
				j++;
			}
		}
	}
}
int main()
{
	string a, b[100];
	int n;
	getline(cin, a);
	cin >> judge >> n;	
	for(int i = 0; i <= n; i ++){
		getline(cin, b[i]);	
	}
	for(int j = 0; j <= n; j ++){
		kmp_search(b[j], a);
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/106795950