实现一个挺高级的字符匹配算法:
给一串很长字符串,要求找到符合要求的字符串,例如目的串:1231******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);
}
}