跳转到内容

算法实现/字符串/最长公共前缀/后缀子串

来自维基教科书,开放书籍,开放世界

此算法是最长公共子串算法的特例。前缀(或后缀)的特例带来了显著的性能提升 - 在我的应用程序中,性能提高了大约两个数量级。

不幸的是,目前我只提供了 Perl 版本,因为这是我的项目所需的!我希望其他需要此算法的其他语言的人能够在这里记录他们的实现。

最长公共前缀和后缀子串

[编辑 | 编辑源代码]
    public static string LCS_start(string word1, string word2)
    {
      int end1 = word1.Length - 1;
      int end2 = word2.Length - 1;

      int pos = 0;

      while (pos <= end1 && pos <= end2)
      {
        if (word1[pos] != word2[pos])
        {
          pos++;
        }
      }
      return word1.Substring(0,pos);
    }

    public static string LCS_end(string word1, string word2)
    {
      int pos1 = word1.Length - 1;
      int pos2 = word2.Length - 1;

      while (pos1 >= 0 && pos2 >= 0)
      {
        if (word1[pos1] != word2[pos2])
        {
          pos1--;
          pos2--;
        }
      }
      return word1.Substring(pos1 + 1);
    }

Javascript

[编辑 | 编辑源代码]

最长公共前缀和后缀子串

[编辑 | 编辑源代码]
function LCS_start( word1,  word2) {

  let end1 = word1.length - 1
  let end2 = word2.length - 1

  let pos = 0

  while (pos <= end1 && pos <= end2){
    if (word1[pos] != word2[pos]) {
       return word1.substring(0,pos)
    } else {
        pos++
    }
  }
}

function LCS_end( word1,  word2) {

  let pos1 = word1.length - 1
  let pos2 = word2.length - 1

  while (pos1 >= 0 && pos2 >= 0){
    if (word1[pos1] != word2[pos2]) {
       return word1.substring(pos1 + 1)
    } else {
        pos1--
        pos2--
    }
  }
}

最长公共前缀子串

[编辑 | 编辑源代码]
sub lcl_substr
{
  my $s1 = shift;
  my $s2 = shift;

  my $end1 = length($s1) - 1;
  my $end2 = length($s2) - 1;

  my $pos = 0;

  while ($pos <= $end1 && $pos <= $end2)
  {
   last if substr($s1, $pos, 1) ne substr($s2, $pos, 1);
   $pos++;
  }

  return substr($s1, 0, $pos);
}

最长公共后缀子串

[编辑 | 编辑源代码]
sub lct_substr
{
  my $s1 = shift;
  my $s2 = shift;

  my $pos1 = length($s1) - 1;
  my $pos2 = length($s2) - 1;

  while ($pos1 >= 0 && $pos2 >= 0)
  {
   last if substr($s1, $pos1, 1) ne substr($s2, $pos2, 1);
   $pos1--;
   $pos2--;
  }

  return substr($s1, $pos1+1);
}

最长公共前缀子串

[编辑 | 编辑源代码]
def longest_common_leading_substring(string1, string2):

  common = ''
  for s1, s2 in zip(string1, string2):
    if s1 == s2:
      common += s1
  return common

最长公共后缀子串

[编辑 | 编辑源代码]
def longest_common_trailing_substring(string1, string2):

  common = ''
  for s1, s2 in zip(string1[-1::-1], string2[-1::-1]):
    if s1 == s2:
      common += s1
  return common[-1::-1]


华夏公益教科书