两个字符串的最大相同子串

两个字符串的最大相同子串

 1 public class TestsonString {
 2     public static void main(String[] args) {
 3         String s1 = "asdfkljasdCCTVCCTVfioejsdfunbsdfhh";
 4         String s2 = "asdfkasdiCCTVCCTVufasdfjh";
 5         sonStringOperation(s1,s2);
 6         
 7         System.out.println("\n================================================");
 8         
 9         String s3 = "abcdefgdcba";
10         String s4 = "asdabcdfkasdiCCTVCCTVufasdfdcbajh";
11         sonStringOperation(s3,s4);
12     }
13 
14     private static void sonStringOperation(String s1,String s2) {
15         String temp,s3; 
16         if (s1.length() < s2.length()) {// 比较s1与s2长度,将较长的字符串赋给s1
17             temp = s2;
18             s2 = s1;
19             s1 = temp;
20         }
21         int count = s2.length();// 将较短字符串的长度赋值给count
22         int sum = (count + 1) * count / 2;// 计算得出所有可能结果的最大值sum
23         String[] sonArray = new String[sum];// 分配sum个空间给sonArray数组
24         int arrIndex = 0;// sonArray数组下标
25         if (s1.contains(s2)) {
26             System.out.println("最大子字符串为" + s2);
27         } else if (!s1.contains(s2)) {
28             for (int i = 0; i < s2.length(); i++) {
29                 for (int j = s2.length(); j > i; j--) {
30                     s3 = s2.substring(i, j);// 将截取后的字符串赋值给s3
31                     if (s1.contains(s3)) {// 如果s3为s1的子字符串,则将s3置入sonArray数组中
32                         sonArray[arrIndex] = s3;
33                         arrIndex++;
34                     }
35                 }
36             }
37             if (sonArray[0] == null) {// 如果sonArray数组为空
38                 System.out.println("两个字符串之间没有相同的子字符串!");
39                 return;
40             }
41             temp = sonArray[0];
42             count = 0;
43             for (int i = 1; i < arrIndex; i++) {
44                 if (temp.length() < sonArray[i].length()) {
45                     temp = sonArray[i];
46                     count = 1;
47                 }else if(temp.length() == sonArray[i].length()) {
48                     count++;
49                 }
50             }
51             System.out.print("两个字符串的相同的最大子字符串为:");
52             for (int i = 0; i < arrIndex; i++) {
53                 if(temp.length()==sonArray[i].length())
54                     System.out.print(sonArray[i]+" ");
55             }
56         }
57     }
58 }

 

posted @ 2018-11-17 21:57 书书数数 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值