Obtains all the common substrings of two strings.

Source: Internet
Author: User

Obtains all the common substrings of two strings.

Application Scenario: obtain all the common substrings of two strings.

Idea: 1. first obtain the intersection of two substrings

2. traverse the intersection substring from the shortest substring to the oldest substring

 

 

public static List
 
   getAllCommonSubStrings(String str1, String str2) {        //TODO null check.                String longString = str1;        String shortString = str2;        if(str1.length() < str2.length()){            longString = str2;            shortString = str1;        }                List
  
    result = new ArrayList
   
    ();        List
    
      vacancy = new ArrayList
     
      ();        vacancy.add();                List
      
        list1 = Arrays.asList(shortString.split()); List
       
         list2 = Arrays.asList(longString.split()); result.addAll(list1); result.retainAll(list2); result.removeAll(vacancy); List
        
          commonSubStrings = new ArrayList
         
          (); StringBuffer strBuf = new StringBuffer(); for(int i = 0; i < result.size()-1; i++){ strBuf = strBuf.append(result.get(i)); if(shortString.contains(strBuf + result.get(i+1)) && longString.contains(strBuf + result.get(i+1)) && i < result.size()-2){ continue; }else{ commonSubStrings.add(strBuf.toString()); strBuf = new StringBuffer(); } } String tail = commonSubStrings.get(commonSubStrings.size()-1)+ result.get(result.size()-1); if(shortString.contains(tail) && longString.contains(tail)){ commonSubStrings.set(commonSubStrings.size()-1, tail); }else{ commonSubStrings.add(result.get(result.size()-1)); } return commonSubStrings; }
         
        
       
      
     
    
   
  
 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.