[LeetCode] Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
思路:
这道题其实很简单,但是比较别扭的是这道题不是一般情况下的按层来遍历,而是按列来遍历。可以考虑用第一个string做外层loop,需要注意的是各个string的长短不一样,所以inner loop务必check index。
注意:
break只能break一层loop
class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) return ""; if (strs.length == 1) return strs[0]; int i = 0, j = 0; for (i = 0; i < strs[0].length(); i++) { char c = strs[0].charAt(i); for (j = 0; j < strs.length; j++) { if (i >= strs[j].length() || strs[j].charAt(i) != c) return strs[0].substring(0, i); } } return strs[0]; } }
python version
找到最短的str这个写法很实用
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if strs is None or len(strs) == 0: return '' shortest = min(strs, key=len) for i, ch in enumerate(shortest): for a_str in strs: if a_str[i] != ch: return shortest[:i] return shortest
posted on 2018-03-20 11:30 codingEskimo 阅读(149) 评论(0) 收藏 举报
浙公网安备 33010602011771号