java查找最短匹配字符串_java – 查找包含给定单词的最短子字符串的方法:需要优化...

我有一个程序,要求我找到给定String的最短子段,包含一个单词列表.即使我的程序是正确的,我也无法在执行的时间范围内(5秒)交付.我认为问题是由于我使用的复杂(平凡)算法.它由嵌套循环组成,需要多次扫描list_of_words数组.这是我的搜索功能代码. a []包含原始字符串,由单词存储,b []包含要找到的单词列表以形成子段. String gstores临时子段由原始字符串中的单词组成,包括列表中的单词.

private static void search() // Function to find the subsegment with a required list of words

{

int tail,x;//counters

String c[]=new String[b.length]; //initializing a temporary array to copy the list of words array.

for(int i =0; i

{

System.arraycopy(b, 0, c, 0, b.length);//copying the list of words array to the temporary array

for (int j=0;j

{

x=0; //counter for temporary array

if(a[i].equalsIgnoreCase(b[j]))//checking for a match with list of words

{

tail=i;

//adds the words starting from the position of the first found word(tail) till all the words from the list are found

while((x

{

g=g+" "+a[tail];//adds the words in the string g

for(int k=0;k

{

if(c[k].equalsIgnoreCase(a[tail]))

{

c[k]=""; x++;

}

}

tail++;

}

if((tail==a.length)&&(x!=b.length))//checks if the string g does not contains all the listed word

{

g="";

}

else

{

count(g);g="";//check for the shortest string.

}

}

}

}print();

}

样品:

原始字符串:这是一个测试.这是一个编程测试.这是一个编程测试.

可以找到的词:this,test,a,programming.

子分段:

这是一个测试这是一个编程

这是一个编程测试

编程测试一个编程测试

编程测试这个编程测试

测试一个编程测试

编程测试这个

最短子段:编程测试

关于数据结构或循环结构的变化的任何建议,或甚至优化相同的算法的变化都将是有帮助的.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值