今天看到一道算法题:给定一长一短的俩个字符串A,B,假设A长B短,现在,要你判断B是否包含在字符串A中。
比如,如果是下面两个字符串:
String 1: ABCDEFGHLMNOPQRS
String 2: DCGSRQPOM
答案是true,所有在string2里的字母string1也都有。
如果是下面两个字符串:
String 1: ABCDEFGHLMNOPQRS
String 2: DCGSRQPOZ
答案是false,因为第二个字符串里的Z字母不在第一个字符串里。
我们很容易想到的一个算法就是轮询,每次取短字符串中的字符在长字符串中找。
方法1:
public class stringIn {
public boolean compareStr(String strLong,String strShort){
char[] tempLong = new char[strLong.length()];
char[] tempShort = new char[strShort.length()];
int i,j;
strLong.getChars(0, strLong.length(), tempLong, 0);
strShort.getChars(0, strShort.length(), tempShort, 0);
for(i=0;i<tempShort.length;i++){
for(j=0;j<tempLong.length;j++){
if(tempShort[i]==tempLong[j]){
break;
}
}
//当long数组循环完毕还没匹配则说明不包含
if(j==tempLong.length){
System.out.println("NO");
return false;
}
}
System.out.println("YES");
return true;
}
public static void main(String[] args) {
stringIn s=new stringIn();
String strLong="abcdefg";
String strShort="al";
s.compareStr(strLong, strShort);
}
}
这种算法复杂度为O(段字符串长度*长字符串长度)
方法2:
这种方法是在方法1的基础上改进的,我们可以先对两个字符串进行快速排序,然后再进行轮询,这样复杂度就变成O(mlogm)+O(nlogn)+O(m+n),随着字符串长度的增加,这个算法的优势就越来越明显。