LEETCODEEasy
Longest Common Prefix
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 <= 2000 <= strs[i].length <= 200strs[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
}복사됨