关于公共子串的分析,求两个字符串中所有公共子串个数,以及最长公共子串和长度。

来源:互联网 发布:辐射4捏脸载入json 编辑:程序博客网 时间:2024/05/18 09:51

题目:给出两个字符串,需要计算它们所有公共子串的个数,以及其中最长公共子串和长度值。并用空格隔开;如果没有,则输出为0.

思路:对于输入,因为题目为一行输入,所以定义String数组储存,并用空格隔开两个字符串。第一个数组为第一个字符串,第二个数组为第二个字符串。分别用a[0],a[1]表示,并赋值给String字符串。
          两个字符串中求最长公共字符串,先选取出两个中较长的字符串,对于短的字符串进行依次遍历,判断出长字符串包含短字符串最大长度。并将计数+1,进行循环,直到满足两个字符串中短字符串的长度,
        备注:网上笔试题,代码是参考网上别人的,具体出处找不到了,请谅解。摘抄记录下来方便日后学习。如果有问题尽请批评指正,希望可以和大神一起交流。
java代码如下:
import java.util.Scanner;public class Main03 {// 求解两个字符号的最长公共子串      public static void maxSubstring(String strOne, String strTwo){          // 参数检查          if(strOne==null || strTwo == null){              System.out.println(0);          }          if(strOne.equals("") || strTwo.equals("")){             System.out.println(0);         }          // 二者中较长的字符串          String max = "";          // 二者中较短的字符串          String min = "";          if(strOne.length() < strTwo.length()){              max = strTwo;              min = strOne;          } else{              max = strTwo;              min = strOne;          }          String current = "";          Boolean bool =true;        String temp="";        int count=0;        // 遍历较短的字符串,并依次减少短字符串的字符数量,判断长字符是否包含该子串          for(int i=0; i<min.length(); i++){              for(int begin=0, end=min.length()-i; end<=min.length(); begin++, end++){                  current = min.substring(begin, end);                  if(max.contains(current)){                  count++;                if(bool)                                {                temp=current;                bool =false;                }                                    }              }          }         System.out.println(count+" "+temp.length());        //输出最大公共长度的字符串        System.out.println(temp);           }            public static void main(String[] args) {      Scanner in = new Scanner(System.in);        while(in.hasNext())        {    String  aa = in.nextLine();    String[] a = aa.trim().split(" ");        String m =a[0];    String n =a[1];    new Main03().maxSubstring(m, n);    }        }  }

样例输入:
abc edg
abc a
abc ab
样例输出:
0 0
1 1 
 3 2
阅读全文
0 0
原创粉丝点击