每周一道算法题011:最长公共子串

问题:

求以下几组单词的最长公共子串的长度
1.fish和fosh
2.fish和hish
3.fish和vista

思路:

可以用表格法,横纵坐标分别是两个单词,如果字符相同,就用左上角的数字加1,最后取表格中的最大值。

解答:

php:

<?php

// 找出两个单词的最长公共子串
function findLongestSubString($word1, $word2)
{
    $len1 = strlen($word1);
    $len2 = strlen($word2);
    $cell = array();
    for ($i = 0; $i < $len1; $i++) {
        for ($j = 0; $j < $len2; $j++) {

            // 如果两个字符相同,则取其左上角的数值+1
            if ($word1[$i] == $word2[$j]) {
                if ($i > 0 && $j > 0) {
                    $cell[$i][$j] = $cell[$i - 1][$j - 1] + 1;
                } else {
                    $cell[$i][$j] = 1;
                }
            } else {
                $cell[$i][$j] = 0;
            }
        }
    }
    printCell($word1, $word2, $cell);
    $maxLength = findMaxValue($cell);
    echo $maxLength . "\n";
}

// 找出值最大的单元格
function findMaxValue($cell)
{
    $max = 0;
    foreach ($cell as $rows) {
        foreach ($rows as $item) {
            if ($item > $max) {
                $max = $item;
            }
        }
    }
    return $max;
}

function printCell($word1, $word2, $cell)
{
    $len1 = strlen($word1);
    $len2 = strlen($word2);
    echo "  ";
    for ($i = 0; $i < $len2; $i++) {
        echo $word2[$i] . " ";
    }
    echo "\n";
    for ($i = 0; $i < $len1; $i++) {
        echo $word1[$i] . " ";
        echo implode(' ', $cell[$i]) . "\n";
    }

}

findLongestSubString("fish", "fosh");
findLongestSubString("fish", "hish");
findLongestSubString("hish", "vista");

输出:

  f o s h 
f 1 0 0 0
i 0 0 0 0
s 0 0 1 0
h 0 0 0 2
2
  h i s h 
f 0 0 0 0
i 0 1 0 0
s 0 0 2 0
h 1 0 0 3
3
  v i s t a 
h 0 0 0 0 0
i 0 1 0 0 0
s 0 0 2 0 0
h 0 0 0 0 0
2

golang:

package main

import "fmt"

func main() {
    findLongestSubString("fish", "fosh")
    findLongestSubString("fish", "hish")
    findLongestSubString("fish", "vista")
}

func findLongestSubString(word1, word2 string) {
    len1 := len(word1)
    len2 := len(word2)
    cell := make([][]int, len1)
    for i := 0; i < len1; i++ {
        cell[i] = make([]int, len2)
        for j := 0; j < len2; j++ {
            if word1[i] == word2[j] {
                if i > 0 && j > 0 {
                    cell[i][j] = cell[i-1][j-1] + 1
                }else{
                    cell[i][j] = 1
                }
            }
        }
    }
    val := findMaxValue(cell)
    fmt.Println(val)
}

func findMaxValue(cell [][]int) int {
    max := 0
    for _, rows := range cell {
        for _, item := range rows {
            if item > max {
                max = item
            }
        }
    }
    return max
}

输出:

2
3
2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值