字符串匹配

1. 利用正则表达式取巧

public class Main
{
	static Set<String> set = new HashSet<String>(); // 存放B可能代表的字符串
	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		// 从输入流中读数据
		String strA = sc.nextLine().trim();
		String strB = sc.nextLine().trim();
		
		// 如果字符串strB比strA更长
		if (strB.length() > strA.length())
		{
			System.out.println(0);
			return;
		}
		
		// 将所有的?替换成.
		strB = strB.replace('?', '.');
		
		//  编译正则表达式
		Pattern p = Pattern.compile(strB);
		// 使用pattern对strA进行匹配
		Matcher m = p.matcher(strA);
		
		int startIndex = 0; // 搜索的起始下标
		int endIndex = strA.length(); // 要搜索的字符串的长度
		while (startIndex < endIndex && m.find(startIndex))
		{
			set.add(m.group(0)); // 将匹配到的整个串中的内容放到set中
			startIndex++;
		}
		// 打印匹配的字符串的种数
		System.out.println(set.size());
	}
}

2. 常规思路(KMP)

public class Main
{
	static Set<String> set = new HashSet<String>(); // 存放B可能代表的字符串
	public static void main(String[] args)
	{
		Scanner scan = new  Scanner(System.in);
		// 得到字符串A和B
		String strA = scan.nextLine().trim();
		String strB = scan.nextLine().trim();
		
		// 计算字符串A和B的长度
		int lenA = strA.length();
		int lenB = strB.length();
				
		// 如果字符串strB比strA更长
		if (lenB > lenA)
		{
			System.out.println(0);
			return;
		}
		
		int scope = lenA-lenB+1;// 有效搜索范围
		String subStr = null; // 子串
		boolean flag = true; 
		
		for (int i=0; i<scope; i++) 
		{
			subStr = strA.substring(i, i+lenB);
			flag = true;
			// 逐个检查字符是否匹配
			for (int j=0; j<lenB; j++)
			{
				if (strB.charAt(j) == '?')
					continue;
				
				if (subStr.charAt(j) != strB.charAt(j))
				{
					flag = false; // 表示不匹配
					break;
				}
			}
			if (flag == true)
				set.add(subStr);
		}
		// 输出匹配的字符串种数
		System.out.println(set.size());
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值