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.
题目大意:寻找输入字符串中最长的公共前缀,若有,则输出前缀;若无,则输出空。
解题思路:字符串问题上一篇博客说到过,用Python解决字符串问题是相对便捷的
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not str:
return ""
res = ""
for i in range(0,len(strs[0])):
for j in xrange(1, len(strs)):
if i >= len(strs[j]) or strs[j][i] != strs[0][i]:
return res
res += strs[0][i]
return res