我们需要找到一个字符串中包含另一个字符串的某个字谜作为子序列的子串数量。
只有当起始位置或结束位置不同的情况下,才认为这些子串是不同的。
String="aba"
anotherString="a"
Occurence of "a" in "aba" is as follows :
a at index 0..0
ab at index 0..1
aba at index 0..2
ba at index 1..2
a at index 2..2
i.e total of 5 times...so o/p=5
(the start and end points here, are inclusive)
我认为这个问题涉及到“字符串中子序列的出现次数”和“查找包含另一个字符串所有字符的最小窗口”的应用之一。
但是,即使我在合并代码时进行了许多更改,我仍然无法得出解决方案。将我的代码粘贴过来是没有用的,因为我知道我错在哪里。我想知道的是,我们如何在不使用蛮力解决方案的情况下有效地解决这个问题。
代码:
public static void findLengthAndSequence(String str1,String str2){
int begin=0,biginWith=0,endWith=0,count=0,minLen=Integer.MAX_VALUE,len=0;
int l=0;
int [] hasFound=new int[256];
int [] toFound=new int[256];
for(int i=0;i<str2.length();++i){
toFound[(int)str2.charAt(i)]++;
}
for(int end=0;end<str1.length();++end){
if(toFound[(int)str1.charAt(end)]==0)
continue;
hasFound[(int)str1.charAt(end)]++;
if(hasFound[(int)str1.charAt(end)]<=toFound[(int)str1.charAt(end)]){
count++;
}
if(count==str2.length()){
l++; //add this to find number of such anagram in string
System.out.println("l= "+l+" "+begin+" "+end);
while(toFound[(int)str1.charAt(begin)]==0 || hasFound[(int)str1.charAt(begin)]>toFound[(int)str1.charAt(begin)] )
{
if(hasFound[(int)str1.charAt(begin)]>toFound[(int)str1.charAt(begin)]){
hasFound[(int)str1.charAt(begin)]-=1;
}
begin++;
}//while
len=end-begin+1;
if(minLen>len){
minLen=len;
endWith=end;
biginWith=begin;
}
}//if
}//end
for(int i=biginWith;i<=endWith;++i){
System.out.print(""+str1.charAt(i));
}
}
这段代码会输出3,即上面的问题的答案。 我知道一旦遍历完第一个字符串并到达末尾,我就无法检查每个子字符串了。
e.g in "aba" my code checks for a,ab,aba.but once I reach the end it will not check
ba,a .since we need to count this also as they are having different index values.
除了指数时间复杂度的蛮力方法,还有其他方法可以检查每个可能的子字符串吗?
n
的字符串中,恰好有n * (n - 1) / 2
个子字符串。这显然是一个多项式。 - kraskevich