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[]} strs3 * @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 res11 }12 for (const char of min) {13 let temp = res + char14 const isPrefixOfAll = strs.every(str => str.startsWith(temp))15 if (isPrefixOfAll) {16 res = temp17 } else {18 break19 }20 }21 return res22}
References
Comments
Loading comments...
Tags
leetcode
string
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Valid Palindrome
Feb 5, 2021
Previous Post
LeetCode: Valid Anagram
Feb 5, 2021