LeetCode每日一练【14】

Longest Common Prefix

思路

  1. 找到原始字符串数组中长度最小的元素作为通用字符串res

  2. 遍历字符串数组, 比对元素和res的通用字符串

    • 如果相同, 不做操作
    • 如果不相同, 对res进行切片处理, 跳出当前循环
  3. 返回res

代码

/*
 * @Author: fox
 * @Date: 2022-04-30 11:16:38
 * @LastEditors: fox
 * @LastEditTime: 2022-04-30 17:17:30
 * @Description: https://leetcode.com/problems/longest-common-prefix/
 */


/**
 * @param {string[]} strs 字符串数组
 * @return {string} 字符串数组元素通用前缀
 */
const longestCommonPrefix = (strs) => {
    console.log(strs)
    const mapStrs = strs.map(item => item.length) // 元素长度映射数字组
    const minLen = Math.min(...mapStrs); // 映射数组中最短的字符串长度
    let res = strs[mapStrs.indexOf(minLen)] // 获取最短的字符串元素
    
    for (let i = 0; i < strs.length; i++) {
        for (let j = 0; j < strs[i].length; j++) {
            if (!res || !res.length) {
                return res
            }
            if (res[j] !== strs[i][j]) {
                res = res.slice(0, j)
                break;
            }
        }
    }

    return res
};

let strs;

strs = ["flower","flow","flight"]
console.log(longestCommonPrefix(strs)) // 'fl'

strs = ["dog","racecar","car"]
console.log(longestCommonPrefix(strs)) // ''

strs = ["ab", "a"]
console.log(longestCommonPrefix(strs)) // 'a'

strs = ["reflower","flow","flight"]
console.log(longestCommonPrefix(strs)) // ''
posted @ 2022-04-30 17:37  白い故雪  阅读(29)  评论(0编辑  收藏  举报