zoukankan      html  css  js  c++  java
  • [Lintcode]Longest Common Substring

    Longest Common Substring题解

    原创文章,拒绝转载

    题目来源:http://www.lintcode.com/en/problem/longest-common-substring/


    Description

    Given two strings, find the longest common substring.

    Return the length of it.

    Notice
    
    The characters in substring should occur continuously in original string. This is different with subsequence.
    

    Example

    Given A = "ABCD", B = "CBCE", return 2.

    Solution

    class Solution {
    private:
        int count;
        int row, col;
        vector<vector<bool> > matrix;
    public:
        void updateCount(int r, int c) {
            bool flag = false;
            int tempCount = 0;
            while (r < row && c < col) {
                if (matrix[r][c]) {
                    if (!flag)
                        flag = true;
                    tempCount++;
                } else if (flag) {
                    if (tempCount > count)
                        count = tempCount;
                    flag = false;
                    tempCount = 0;
                }
                r++;
                c++;
            }
            if (flag && tempCount > count)
                count = tempCount;
        }
        int longestCommonSubstring(string& x, string& y) {
            if (x.empty() || y.empty())
                return 0;
            row = x.length();
            col = y.length();
            count = 0;
            matrix = vector<vector<bool> >(row, vector<bool>(col, false));
    
            int i, j;
            for (i = 0; i < row; i++) {
                for (j = 0; j < col; j++) {
                    if (x[i] == y[j])
                        matrix[i][j] = true;
                }
            }
    
            // test
            // printMatrix(matrix);
            
            int r, c;
            bool flag;
            for (j = 0; j < col; j++) {
                r = 0;
                c = j;
                updateCount(r, c);
            }
    
            for (i = 1; i < row; i++) {
                r = i;
                c = 0;
                updateCount(r, c);
            }
    
            return count;
        }
    };
    
    

    解题描述

    这道题是经典的求两个字符串的最长公共子字符串。我采用的是相对暴力的解法:给出一个矩阵,长度和宽度分别是两个字符串的长度,其中的项目用于标记两个字符串对应位置上的字符是否相同。标记完之后对矩阵的对角线进行扫描,找到最长的连续标记值的长度。

    而事实上寻找最长公共子字符串最高效的算法是KMP算法

  • 相关阅读:
    分享一下前一段时间的开发总结
    循环,梦
    从C#程序中调用非受管DLLs
    大学生零工资就业,谁之过?
    国外宽带用户的上网速度能达到多少呢?
    天沉沉,来个好天气吧
    虚伪,不只是形容一个人
    回头思考关于xml的使用
    从毕业生当中看人与人的差距
    C# 编码规则
  • 原文地址:https://www.cnblogs.com/yanhewu/p/7822696.html
Copyright © 2011-2022 走看看