zoukankan      html  css  js  c++  java
  • Java 练习(获取两个字符串中最大相同子串)

    package com.klvchen.exer;
    
    import org.junit.Test;
    
    import java.util.Arrays;
    
    public class StringDemo2 {
        /*
        获取两个字符串中最大相同子串,比如:
        str1 = "abcwerthelloyuiodef" ; str2 = "cvhellobnm"
        提示:将短的那个串进行长度依次递减的子串与较长的串比较。
         */
    
        public String getMaxSameString(String str1, String str2){
            String maxStr = (str1.length() >= str2.length())? str1 : str2;
            String minStr = (str1.length() <  str2.length())? str1 : str2;
            int length = minStr.length();
    
            for (int i = 0; i < length; i++){
                for (int x = 0, y = length - i; y <= length; x++, y++){
                    String subStr = minStr.substring(x, y);
                    if (maxStr.contains(subStr)){
                        return subStr;
                    }
                }
            }
    
            return null;
        }
    
        // 如果存在多个长度相同的最大相同子串
        // 此时先返回 String[], 后面可以用集合中的 ArrayList 替换,较方便
        public String[] getMaxSameString1(String str1, String str2){
            if (str1 != null && str2 != null){
                StringBuffer sBuffer = new StringBuffer();
                String maxString = (str1.length() > str2.length()) ? str1 : str2;
                String minString = (str1.length() > str2.length()) ? str2 : str1;
    
                int len = minString.length();
                for (int i = 0; i < len; i++){
                    for (int x = 0, y = len - i; y <= len; x++, y++){
                        String subString = minString.substring(x, y);
                        if (maxString.contains(subString)){
                            sBuffer.append(subString + ",");
                        }
                    }
    //                System.out.println(sBuffer);
                    if (sBuffer.length() != 0){
                        break;
                    }
                }
                String[] split = sBuffer.toString().replaceAll(",$", "").split("\,");
                return split;
            }
    
            return null;
        }
    
        @Test
        public void testGetMaxSameString(){
            String str1 = "abcwerthelloyuiodef";
            String str2 = "cvhellobnm";
            String[] maxSameStrings = getMaxSameString1(str1, str2);
            System.out.println(Arrays.toString(maxSameStrings));
        }
    }
    

  • 相关阅读:
    从MVC和三层架构说到ssh整合开发-下
    Codeforces Round #226 (Div. 2)--A Bear and Raspberry
    ISA95的抽象惯例
    Difference between End-to-end testing and System testing
    javascript Date format(js日期格式化)
    给easyui datebox扩展一个清空按钮
    easyui combobox开启搜索自动完成功能
    给你的webstorm添加快速生成注释得快捷键
    location.origin兼容IE
    将json转换成struts参数
  • 原文地址:https://www.cnblogs.com/klvchen/p/15220519.html
Copyright © 2011-2022 走看看