Skip to content

Latest commit

 

History

History
executable file
·
64 lines (47 loc) · 1.17 KB

0014._Longest_Common_Prefix.md

File metadata and controls

executable file
·
64 lines (47 loc) · 1.17 KB

014. Longest Common Prefix

难度: Easy

刷题内容

原题连接

内容描述

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:

All given inputs are in lowercase letters a-z.

解题方案

思路 - 时间复杂度: O(N)- 空间复杂度: O(N)******

代码:

/**
 * @param {string[]} strs
 * @return {string}
 */
let longestCommonPrefix = function(strs) {
    let firstStr = strs[0];
    let result ='';
    if(!strs.length){
        return result;
    }
    for (let i = 0; i < firstStr.length; i++) {
        for (let j =  1; j < strs.length; j++) {
            if(firstStr.charAt(i) !== strs[j].charAt(i)){
                return result;
            }
        }
        result = result + firstStr.charAt(i);
    }
    return result;

};