Finding the longest common subsequence in C++/python

Posted by islan on Sun, 30 Jan 2022 06:44:11 +0100

C + + finding the longest common subsequence

1. Transverse scanning

 

2. Longitudinal scanning

Problem solving ideas
If there is no string, an empty string is returned; If there is only one string, return itself.

Otherwise, take strs[0] as the standard and compare the remaining strings one by one for each character. If it is found that there is not enough length (or strs[i].size() length = lengh, it proves that the string strs[i] has reached the end), or if the characters are not matched, it ends locally and returns the substring that has been qualified by comparison so far.

If all the characters of strs[0] are compared, return to itself.

O(NM)O(NM), very good* NN and MM are the number of strings and the length of the shortest string respectively.

Author: hexiaozhidi
Link: https://leetcode-cn.com/problems/longest-common-prefix/solution/14-zui-chang-gong-gong-qian-zhui-mo-ni-c-36kk/
Source: LeetCode
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

C + + version

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.size() == 0)//String length is 0
            return "";
        if (strs.size() == 1)//The string is just one element
            return strs[0];

        //strs[0].size(): refers to the length of the element, STRs Size (): refers to the number of elements in the whole string array
        
        for (int length = 0; length < strs[0].size(); ++length)//Column: take the characters on each bit of the element
            for (int i = 1; i < strs.size(); ++i)//Line: take the overall value of each element

                //End flag: the character at the end of an element string or the position of two elements in vertical comparison is different
                if (length == strs[i].size() || strs[i][length] != strs[0][length])
                    return strs[0].substr(0, length);
        return strs[0];//If you can return from here, it proves that all characters of the first element are subsequences
    }
};

python version

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ''
        strLen = [len(str) for str in strs] //Find the list with element length as the element
        minLen = min(strLen)  //Find the length of the shortest string in strs
        n = len(strs) //Number of strings

        if minLen == 0:
            return ''

        for i in range(minLen)://The first layer, for, scans the shortest string in strs by column
            for j in range(1, n): //strs has n strings in total, scanning horizontally from the second one
                if strs[j][i] != strs[j - 1][i]://If the characters in column i of strs adjacent strings are different
                    return strs[0][:i]  //The returned common string is the 0 - (i-1) th element from the 0 th string
        return strs[strLen.index(minLen)]

Author: michael_chou
 Link: https://leetcode-cn.com/problems/longest-common-prefix/solution/0014-zui-chang-gong-gong-qian-zhui-4chon-76k2/
Source: force buckle( LeetCode)
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

C language version

 

python solves the longest common subsequence

1. Use zip feature

zip (* strs) rearrange strs into a new element in strs according to each column, and then use the set function to rearrange to combine the longest common subsequence.

'''
Parameter interpretation: List[str]As parameter strs The default value of the assignment can be left blank
-> str: The use case shows that the recommended return value of the function is a string str,You can't write, you return If it's not a string, it won't report an error
'''
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        res = ""
        for tmp in zip(*strs)://Skillfully use zip to reorganize a column of characters of each element in strs into an element tmp
            tmp_set = set(tmp)//De duplication of tmp

            //If the length of the tmp element after de duplication is 1, it means that the characters in this column of each element in the original strs are the same
            if len(tmp_set) == 1:
                res += tmp[0] //Add this character to the longest common subsequence
            else:
                break
        return res

Author: michael_chou
 Link: https://leetcode-cn.com/problems/longest-common-prefix/solution/0014-zui-chang-gong-gong-qian-zhui-4chon-76k2/
Source: force buckle( LeetCode)
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

2. Use the characteristics of dictionary order

thinking
First find the string with the smallest and largest dictionary order in the array (the difference between the two is the largest), and the longest common prefix is the common prefix of the two strings

Complexity
Time complexity O(N)O(N), N is the average of all string lengths
Spatial complexity O(1)O(1)

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ''
        str0 = min(strs)
        str1 = max(strs)
        for i in range(len(str0)):
            if str0[i] != str1[i]:
                return str0[:i]
        return str0

Author: michael_chou
 Link: https://leetcode-cn.com/problems/longest-common-prefix/solution/0014-zui-chang-gong-gong-qian-zhui-4chon-76k2/
Source: force buckle( LeetCode)
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

3. Use the find function (transverse scanning method)

1)strs[i].find(s): find the string s in the string STRs [i]. If it is found, the first address subscript will be returned. If it is not found, it will return - 1

This code is compared with 0 to see whether the return subscript is the first address subscript of s string.

2)s[:-1] means that if strs[i] and s do not match, remove the last character of string s and then match strs[i]

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 0:
            return ''
        s = strs[0] //Randomly select the family strs[0] as the initial value of the common subsequence
        for i in range(1, len(strs)):
            //When i=1: find the common subsequence s in strs[0] and strs[1] first. When i=2, find the new common subsequence in strs[2] and s
            while strs[i].find(s) != 0 : 
                s = s[:-1] //Shorten common subsequence s
        return s


Author: huamei
 Link: https://leetcode-cn.com/problems/longest-common-prefix/solution/python-shui-ping-sao-miao-fa-by-huamei/
Source: force buckle( LeetCode)
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

 

Topics: data structure string