leetcode 查找字符串数组共同的前缀longestCommonPrefix
Posted linxf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 查找字符串数组共同的前缀longestCommonPrefix相关的知识,希望对你有一定的参考价值。
我是海大顶瓜瓜
1、从前面查找最长公共前缀
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
function getSameFirst(arr) { let res = ‘‘; let first; let max = arr[0].length; // 第一个循环是遍历字符串的长度 for (let i = 0; i < max; i++) { first = arr[0][i]; // 第二个循环是遍历输入的字符串数组 for (let j = 1,len= arr.length; j < len; j++) { // 把每个字符串拿去一一对比 if (arr[j][i] != first) { console.log(res); return res } } res += first } }
2、从后面查找最长公共字符串
Input: [‘owner‘, ‘flower‘, ‘fighter‘]
Output: "er"
function getSameEnd(arr) { let res = ‘‘; let first = ‘‘; let max = arr[0].length; for (let i = 1; i < max; i++) { // 由于是截取最后的字符,所以用slice来截取 first = arr[0].slice(-i); for (let j = 1,len= arr.length; j < len; j++) { if (arr[j].slice(-i) != first) { console.log(res); return res } } res = first } } getSameEnd([‘ofwnqer‘, ‘oflowqer‘, ‘ofightqer‘])
双重for循环真是费头发,以上就是解法,记录一下
以上是关于leetcode 查找字符串数组共同的前缀longestCommonPrefix的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode练习(Python):字符串类:第14题:最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。