两个字符串的最大公共子串,是一个程序员们常常考到和想到的题目,听讲是当年微软面试时要求做的一个程序,写一个返回两个任意字串中最大公共串的函数,即abcdef 和 qcfbcc 返回值为bc
 

注:你要考虑到字符串中最大公共串相等的问题。
例如
dddabd123456abcdefeeeee
234dddabcdegeeee

 
输出:
dddab
abcde

 

 
  
  1. #!/usr/bin/perl  
  2. use strict;  
  3. use warnings;  
  4. use Data::Dumper;  
  5. my %hash1;  
  6. my %hash2;  
  7. my @arr;  
  8. my $str1 = 'aab12345678';  
  9. my $str2 = 'ab1234yb1234567';  
  10.  $str1 =~ /(.*?)(?{$hash1{$1}=$1})(*F)/;  #强制回朔,列举所有字符串,存入hash
  11.  $str2 =~ /(.*?)(?{$hash2{$1}=$1})(*F)/;  
  12.    for (keys %hash1){  
  13.        my  $k = $_;  
  14.         push  @arr,$k if exists $hash2{$k};      
  15.    }  
  16.    my($max,$min)=sort{length($b) cmp length($a)}@arr;  
  17.    for (@arr){  
  18.     if(length($_)==length($max)){  
  19.         print "$_\n";  
  20.     }  
  21.    }  

output:

b1234567