zerovoids.dev
LEETCODEEasy

Longest Common Prefix

풀이일 2025 · 03 · 27기록 1 ms · 58.0 MB원문 leetcode ↗
ArrayStringTrie
문제

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 lowercase English letters if it is non-empty.
풀이 TypeScript
function longestCommonPrefix(strs: string[]): string {
  
  if(strs.length === 1 ) return strs[0]
  
  let result = ''

  for(let i = 0; i < strs[0].length; i++) {
    const set = new Set(strs.map(str => str[i]))
    if(set.size === 1) {
      result += strs[0][i]
    } else break
  }
  
  return result
}
복사됨