1、获取两个字符串中最大相同子串 解题思路: 1. 较长的字符串不变;
2.将较短的字符串长度递减,用获取到的子字符串去与长字符串比较,是否包含;
3.如果包含,则为其最大子串; 代码:
- package unit5;
- public class maxSubstring {
- //定义判断函数
- public static String mySubstring(String str, String key){
-
- int start, end;
- for(int i=0; i<key.length();i++){//key长度递减
- for(start=0,end=key.length()-1-i;end<key.length();start++,end++){//从左至右取key的子串
- String sub = key.substring(start, end+1);//由于sustring()不去末尾值,顾end要加1
- if(str.indexOf(sub) != -1){
- return sub;
- }
- }
- }
- return "";
- }
- public static void main(String args[]){
- String str = "kgashghellodgoqdghogh";
- String key = "hjhellogg";
- System.out.println("("+ str + ")与" +key+"最大子串为:" + mySubstring(str,key) );
- }
- }
复制代码
|