Friday, August 14, 2015

Leetcode 14. Longest Common Prefix

https://leetcode.com/problems/longest-common-prefix/

Quite simple. Just use one string to compare with other strings, once not match or other string ends, the job is done.

Solution:
# T:O(n) S:O(1)
class Solution:
    # @param {string[]} strs
    # @return {string}
    def longestCommonPrefix(self, strs):
        if strs == []:
            return ''
        for i in xrange(len(strs[0])):
            for str in strs:
                if i >= len(str) or str[i] != strs[0][i]:
                    return strs[0][:i]
        return strs[0]
Run Time: 48 ms

No comments:

Post a Comment