|
| 1 | +/* |
| 2 | + * @Author: Chacha |
| 3 | + * @Date: 2022年05月20日 23:43:32 |
| 4 | + * @Last Modified by: Chacha |
| 5 | + * @Last Modified time: 2022年05月20日 23:44:48 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * 来源:https://leetcode-cn.com/problems/longest-common-prefix/ |
| 10 | + * |
| 11 | + * 14. 最长公共前缀 |
| 12 | + * |
| 13 | + * 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。 |
| 14 | + * |
| 15 | + * 示例 1: |
| 16 | + * 输入:strs = ["flower","flow","flight"] |
| 17 | + * 输出:"fl" |
| 18 | + * |
| 19 | + * 示例 2: |
| 20 | + * 输入:strs = ["dog","racecar","car"] |
| 21 | + * 输出:"" |
| 22 | + * 解释:输入不存在公共前缀。 |
| 23 | + * |
| 24 | + */ |
| 25 | +// 横向扫描 也可以想起 版本比较的算法题,第一个和第二个比较,再拿结果和第三个比较 |
| 26 | +const longestCommonPrefix = (strs) => { |
| 27 | + if (strs.length === 0) { |
| 28 | + return ""; |
| 29 | + } |
| 30 | + |
| 31 | + let prefix = strs[0]; |
| 32 | + const len = strs.length; |
| 33 | + const getPrevfix = (str1, str2) => { |
| 34 | + if (str1.length > str2.length) { |
| 35 | + return getPrevfix(str2, str1); |
| 36 | + } |
| 37 | + |
| 38 | + let i = 0; |
| 39 | + let substrLen = 0; |
| 40 | + const len = str1.length; |
| 41 | + |
| 42 | + while (i < len) { |
| 43 | + if (str1[i] === str2[i]) { |
| 44 | + substrLen++; |
| 45 | + } else { |
| 46 | + break; |
| 47 | + } |
| 48 | + i++; |
| 49 | + } |
| 50 | + |
| 51 | + return str1.substr(0, substrLen); |
| 52 | + }; |
| 53 | + |
| 54 | + for (let i = 1; i < len; i++) { |
| 55 | + prefix = getPrevfix(prefix, strs[i]); |
| 56 | + |
| 57 | + if (prefix === "") { |
| 58 | + return ""; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return prefix; |
| 63 | +}; |
| 64 | + |
| 65 | +console.log(longestCommonPrefix(["flower", "flow", "flight"])); |
0 commit comments