Leetcode - Easy - 14. Longest Common Prefix - Javascript
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: strs = ["flower","flow","flight"] Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
consists of only lower-case English letters.
/** * @param {string[]} strs * @return {string} */ var longestCommonPrefix = function(strs) { result = '' let index = 0; const strsLen = strs.length; while(true) { let isCommon = true; const firstChat = strs[0][index]; for (let i =0; i<strsLen; i++) { const currentChat = strs[i][index]; if (!strs[i][index] || firstChat !== currentChat) { return result; } } result += firstChat; index++; } return result; };
0 意見 :
張貼留言