Leetcode
  • Leetcode
  • 1. Two Sum
  • 7. Reverse Integer
  • 9. Palindrome Number
  • 13. Roman to Integer
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 35. Search Insert Position
  • 53. Maximum Subarray
  • 58. Length of Last Word
  • 66. Plus One
  • 876. Middle of the Linked List
  • 67. Add Binary
  • 69. Sqrt(x)
  • 83. Remove Duplicates from Sorted List
  • 14. Longest Common Prefix
  • 70. Climbing Stairs
  • 100. Same Tree
  • 101. Symmetric Tree
  • 104. Maximum Depth of Binary Tree
  • Untitled
Powered by GitBook
On this page

14. Longest Common Prefix

Previous83. Remove Duplicates from Sorted ListNext70. Climbing Stairs

Last updated 6 years ago

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

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

Solution:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        ret = ''
        if len(strs) == 0:
            return ret
        for ssi in range(len(strs[0])):
            ss = strs[0][ssi]
            for i in range(1, len(strs), 1):
                if ssi > len(strs[i])-1 or ss != strs[i][ssi]:
                    return ret
            ret += strs[0][ssi]
        return ret
https://leetcode.com/problems/longest-common-prefix
/description/