/*
* @lc app=leetcode.cn id=14 lang=typescript
*
* [14] 最长公共前缀
*/
// @lc code=start
function longestCommonPrefix(strs: string[]): string {}
// @lc code=end
- 时间复杂度:
- 空间复杂度:
function longestCommonPrefix(strs: string[]): string {
let [res, i, tmp] = ['', 0, '']
while (true) {
for (const s of strs) {
if (tmp === '') tmp = s[i]
if (s[i] === undefined || s[i] !== tmp) return res
}
;[res, i, tmp] = [res + tmp, i + 1, '']
}
}
test.each([
{ input: { strs: ['flower', 'flow', 'flight'] }, output: 'fl' },
{ input: { strs: ['dog', 'racecar', 'car'] }, output: '' },
])('input: strs = $input.strs', ({ input: { strs }, output }) => {
expect(longestCommonPrefix(strs)).toBe(output)
})