mengjian-github / leetcode

leetcode前端题目笔记
0 stars 0 forks source link

14. 最长公共前缀 #14

Open mengjian-github opened 2 years ago

mengjian-github commented 2 years ago

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

 

示例 1:

输入:strs = ["flower","flow","flight"] 输出:"fl" 示例 2:

输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。

mengjian-github commented 2 years ago

这道题比较简单直观的思路就是纵向去比较,直到找到公共的串为止:

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    let result = '';

    let index = 0;

    let flag = true;

    if (strs.length <= 1) {
        return strs[0] || '';
    }

    while (flag) {
        let c = null;
        for (const str of strs) {
            if (c === null) {
               c = str[index];
           } else if (c !== str[index]) {
               flag = false;
               break;
           } else if (index >= str.length) {
               flag = false;
               break;
           }
        }
        if (flag) {
            result += c;
        }
        index++;
    }

    return result;
};