算法研究之字符串包含

今天看到一道算法题:给定一长一短的俩个字符串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),随着字符串长度的增加,这个算法的优势就越来越明显。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值