获取两个字符串中最大相同子串

/*
*获取两个字符串中最大相同子串。
*  从效率来说肯定是从短的字符串对比长的更高
*  可以先加入一个判断 s1  s2谁更短,用短的字符串进行查找比对
*/

class StringTest3{
	public static void main(String[] args){
		String s1 = "abcwerthelloyuiodef";
		String s2 = "cvhellobnm";
		
		System.out.println(s1);
		System.out.println(s2);
		
		sop(s1,s2);
	}

	public static void sop(String str1,String str2){	
		//临时存储字符串中的子串
		String str;
		
		for(int i = 0;i<str2.length();i++){
			for(int j = 0;j<=i;j++){
				/* 
				*	 因为substring(int beginIndex, int endIndex) 属于半闭半开,取值范围[x,y)。需要注意
				*	 通过内层循环控制substring的beginIndex参数
				*	 第一次是[0,str2.length())
				*	 第二次是[0,str2.length()-1)、[1,str2.length())
				*    第三次是[0,str2.length()-2)、[1,str2.length()-1)、[2,str2.length())
				*	 可以知其规律,通过减去i来控制内层循环每次的值,然后通过j的值逐次递增 
				*/
				str=str2.substring(j,str2.length()-i+j);
				if(str1.contains(str)){
					System.out.println("S1和S2字符串相同的最大子串是:"+str);
					//找到后就结束
					return;
				}
			}
		}
	}
}

发表评论