Algorithm——Longest Common Prefix
Posted bbcfive
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Algorithm——Longest Common Prefix相关的知识,希望对你有一定的参考价值。
Q:
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.
Note:
All given inputs are in lowercase letters a-z
.
A:
/** * @param string[] strs * @return string */ var longestCommonPrefix = function(strs) if (!strs.length) return ‘‘; if (strs.length == 1) return strs[0]; var minest = 0; for (var i = 0; i < strs.length - 1; i++) minest = Math.min(strs[i].length, strs[i+1].length); var index = 0, longest = 0; while(index < minest) for (var i = 0; i < strs.length - 1; i++) if (strs[i][index] !== strs[i+1][index]) longest = index; i = strs.length - 1 index = minest else longest = index + 1; index++; return strs[0].slice(0,longest); ;
因为要追求低复杂度,所以这道题想了很久。本来蛮沮丧的,但看到运行速度第一次达到top11%,还是小开心了一下~
但是内存使用还是比较多,所以还存在很大的优化空间。。。。
以上是关于Algorithm——Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章
动态规划 ---- 最长公共子序列(Longest Common Subsequence, LCS)
SP1811 LCS - Longest Common Substring(后缀自动机)