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循环真是费头发,以上就是解法,记录一下

 

posted @ 2020-04-24 23:36  逆战-顶瓜瓜  阅读(362)  评论(0编辑  收藏  举报