Python 99.22%

  • 0
    1. Set the first string in the list as prefix
    2. Go though the other strings in the list.
      Compare st with prefix until meet the first pair of distinct characters. Reduce prefix to the digit before the pair's index. If there was no any pair of distinct characters, prefix remain prefix[:min(len(st), len(prefix))+1]
    class Solution(object):
        def longestCommonPrefix(self, strs):
            :type strs: List[str]
            :rtype: str
            if not strs: return ''
            if len(strs) == 1:
                return strs[0]
            prefix = strs[0]
            for st in strs:
                if st == '':
                    return ''
                for i in xrange(min(len(st), len(prefix))):
                    if prefix[i] != st[i]:
                        prefix = prefix[:i]
                prefix = prefix[:i+1]
            return prefix

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.