zoukankan      html  css  js  c++  java
  • Java练习之最大相同子串

     1 package string.demo;
     2 /* 需求:找到两个字符串的最长共同子串
     3  * 思路:
     4  * 1.先看短的那个字符串是否在长的那个字符串中,如果存在,短的那个字符串就是最大共同子串
     5  * 2.如果不存在,那么就将短的那个子串进行长度递减的方式取子串,去长串中判断是否存在,如果
     6  *     存在,找到!
     7  * 
     8  */
     9 public class FindMostLargeSubstring
    10 {
    11 
    12     /**
    13      * @param args
    14      */
    15     public static void main(String[] args)
    16     {
    17         String s1 = "qwerabcdtyuiop";
    18         String s2 = "xcabcdvbn";
    19         String s = getMaxSubstring(s1, s2);
    20         System.out.println("s = " + s);
    21     }
    22 
    23     /**
    24      * 获得最大子串
    25      * @param s1
    26      * @param s2
    27      * @return
    28      */
    29     private static String getMaxSubstring(String s1, String s2)
    30     {
    31         String max = null;
    32         String min = null;
    33         max = (s1.length() > s2.length()) ? s1 : s2;
    34         min = max.equals(s1) ? s2 : s1; 
    35         for (int i = 0; i < min.length(); i++)
    36         {
    37             for (int  a = 0, b = min.length() - i; b != min.length() + 1; a++, b++)
    38             {
    39                 // 取短字符串的的子串,并判断该子串在长字符串中是否存在
    40                 String sub = min.substring(a, b);
    41                 if (max.contains(sub))
    42                     return sub;  
    43             }
    44         }
    45         return null;
    46     }
    47 
    48 }
  • 相关阅读:
    Python之路,day16-Python基础
    Python之路,day15-Python基础
    Python之路,day14-Python基础
    django之model操作
    django信号
    django缓存
    CSRF的攻击与防范
    cookie和session
    http协议之Request Headers
    ajax参数详解
  • 原文地址:https://www.cnblogs.com/90zeng/p/java_max_common_substring.html
Copyright © 2011-2022 走看看