Q33、(字符串)

实现一个挺高级的字符匹配算法:

给一串很长字符串,要求找到符合要求的字符串,例如目的串:123

1******3***2 ,12*****3 这些都要找出来

其实就是类似一些和谐系统。。。。。


思路:

现在只有一个有问题的思想:

源串:21362

两个指针head和tail,head在后,tail在前

如果head~tail之间的子字符串包含这些和谐系统,比如head=0,tail=2,那么输出子字符串,head跳至下一个目的串中字符在源串中的位置,即最后一位.

如果不包含,则tail指向它的下一个目的串中字符在源串中的位置

类似于编程之美的那个搜索关键字的题目


但是有个问题:

如果源串是12323,那么

第一次循环输出123,head=0+1=1

这样的话12323就被忽略了...还是没想起来这个算法应该怎么弥补


public class Q33 {
	public static boolean check(int[] record ,char[] test)
	{
		int flag = 1;
		
		for(char ch:test)
		{
			if(record[ch]==0)
			{
				flag = 0;
				break;
			}
		}	
		
		if(flag == 1)
			return true;
		else
			return false;
	}
	
	public static void Out(char[] main,int begin,int end)
	{
		String result = "";
		for(int i = begin;i<=end;i++)
		{
			result += main[i];
		}
		
		System.out.println(result);
	}
	
	public static boolean exists(char ch,char[] test)
	{
		for(char ch1:test)
			if(ch == ch1)
				return true;
		return false;
	}
	public static void search(char[] main,char[] test)
	{
		int[] record = new int[255];
		int head = 0;
		int tail = test.length-1;
		
		for(head = 0;head<main.length&&!exists(main[head], test);head++)
		{}
		
		for(tail = head;tail<head+test.length-1;tail++)
		{
			record[main[tail]] ++;
		}
		record[main[tail]] ++;
		while(tail<main.length)
		{
			if(check(record, test))
			{
				Out(main, head, tail);
				record[main[head]]--;
				for(head++;head<main.length&&!exists(main[head], test);head++)
				{}
			}
			else
			{
				for(tail++;tail<main.length&&!exists(main[tail], test);tail++)
				{}
				if(tail<main.length)
					record[main[tail]]++;
			}
		}
	}
	public static void main(String[] args) {
		char[] main = "2132".toCharArray();
		char[] test = "123".toCharArray();
		
		search(main, test);
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值