LeetCode: Longest Common Prefix Solution

Approach

Sort the strs, get the min length str

Find the longest substr of the min that is the start of all other strs

Implementation

1/**
2 * @param {string[]} strs
3 * @return {string}
4 */
5var longestCommonPrefix = function (strs) {
6 strs.sort((a, b) => a.length - b.length)
7 const min = strs[0]
8 let res = ""
9 if (!min) {
10 return res
11 }
12 for (const char of min) {
13 let temp = res + char
14 const isPrefixOfAll = strs.every(str => str.startsWith(temp))
15 if (isPrefixOfAll) {
16 res = temp
17 } else {
18 break
19 }
20 }
21 return res
22}

References

Original problem

Comments

Loading comments...

Tags

leetcode

string

Next Post

LeetCode: Valid Palindrome

HoningJS

Search Posts