描述
Write a function to find the longest common prefix string amongst an array of strings.
分析
简单题,但容易想复杂。第一反应是用trie树,可以做,但实现较复杂。其实只要按位置依次比对每一个字符串,直到有不相等的情况出现即可。时间复杂度O(n1 + n2 + ...)
,空间复杂度O(1)
。
代码
Python
1 |
class (object): |
Write a function to find the longest common prefix string amongst an array of strings.
简单题,但容易想复杂。第一反应是用trie树,可以做,但实现较复杂。其实只要按位置依次比对每一个字符串,直到有不相等的情况出现即可。时间复杂度O(n1 + n2 + ...)
,空间复杂度O(1)
。
1 |
class (object): |
近期评论