[leetcode]#14. Longest Common Prefix
2017-11-17 09:19
465 查看
题目翻译
写个函数,找出一个字符串数组中所有字符串的最长公共前缀。
题目描述不清晰。。。补充几个例子,比如:
{“a”,”a”,”b”} 返回 “” ,因为三个字符串没有公共前缀;
{“a”, “a”} 返回 “a” 因为它是两个字符串的公共前缀;
{“abca”, “abc”} 返回 “abc”;
{“ac”, “ac”, “a”, “a”} 返回 “a”
很直观的思路,从任意一个字符串开始,扫描该字符串,依次检查其他字符串的同一位置是否是一样的字符,当遇到不一样时则返回当前得到的前缀。
写个函数,找出一个字符串数组中所有字符串的最长公共前缀。
题目描述不清晰。。。补充几个例子,比如:
{“a”,”a”,”b”} 返回 “” ,因为三个字符串没有公共前缀;
{“a”, “a”} 返回 “a” 因为它是两个字符串的公共前缀;
{“abca”, “abc”} 返回 “abc”;
{“ac”, “ac”, “a”, “a”} 返回 “a”
很直观的思路,从任意一个字符串开始,扫描该字符串,依次检查其他字符串的同一位置是否是一样的字符,当遇到不一样时则返回当前得到的前缀。
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' res = '' for i in xrange(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
相关文章推荐
- LeetCode 14 - Longest Common Prefix
- LeetCode之14_Longest Common Prefix
- [leetcode] 14.Longest Common Prefix
- [LeetCode-Java]14. Longest Common Prefix
- leetcode14 Longest Common Prefix
- python写算法题:leetcode: 14. Longest Common Prefix
- LeetCode - 14. Longest Common Prefix
- LeetCode 14. Longest Common Prefix
- LeetCode 14 Longest Common Prefix
- 【LeetCode从零单排】No14.LongestCommonPrefix
- [LeetCode] 14. Longest Common Prefix
- leetcode: 14.Longest Common Prefix
- [leetcode]14. Longest Common Prefix
- [Leetcode 18] 14 Longest Common Prefix
- Leetcode 14 Longest Common Prefix
- leetcode -- 14. Longest Common Prefix
- [Leetcode] 14. Longest Common Prefix
- 【LeetCode 14】 Longest Common Prefix
- leetcode 14: Longest Common Prefix (C#版)
- LeetCode 14.Longest Common Prefix