Longest Common prefix

Source: Internet
Author: User

Write a function to find the longest common prefix string amongst an array of strings.

Analysis:

Find the longest common prefix for a string.

Because you can only search for the prefix, you can use the first string as the basis and compare it with other strings by character until a string has been traversed or encounters an inconsistent character, returns the prefix of the first string so far.

class Solution:    # @return a string    def longestCommonPrefix(self, strs):        if not strs or not strs[0]:            return ""        first = strs[0]        for i in range(len(first)):            for s in strs[1:]:                if i >= len(s) or s[i] != first[i]:                    return first[:i]        return firstif __name__ == ‘__main__‘:    s = Solution()    assert s.longestCommonPrefix([]) == ""    assert s.longestCommonPrefix([""]) == ""    assert s.longestCommonPrefix(["a", "b"]) == ""    assert s.longestCommonPrefix(["aa", "aa"]) == "aa"    print ‘PASS‘

Summary:

This problem is relatively simple, and there are not many traps in programming. You can write the code by using an intuitive method to access it.

Longest Common prefix

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.