给定两个字符串str1和str2,输出两个字符串的最长公共子串
    题目保证str1和str2的最长公共子串存在且唯一。
    image.png

    1. //时空Omn
    2. func LCS( str1 string , str2 string ) string {
    3. m, n := len(str1), len(str2) //行,列
    4. res, end := 0, 0
    5. dp := make([][]int, m+1)
    6. for i:= range dp {
    7. dp[i] = make([]int, n+1)
    8. }
    9. for i:=1; i <= m; i++{
    10. for j:=1; j <= n; j++{
    11. if str1[i-1] == str2[j-1] {
    12. dp[i][j] = dp[i-1][j-1] + 1
    13. } else {
    14. dp[i][j] = 0
    15. }
    16. if dp[i][j] > res {
    17. res = dp[i][j]
    18. end = i // 注意
    19. }
    20. }
    21. }
    22. if res == 0 {
    23. return ""
    24. }
    25. return str1[end-res: end]
    26. }