add: 最长公共前缀
This commit is contained in:
parent
581a96e795
commit
8ca4a189f8
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@ -26,6 +26,8 @@
|
||||
"preorder",
|
||||
"pwwkew",
|
||||
"qian",
|
||||
"racecar",
|
||||
"strs",
|
||||
"subarray",
|
||||
"subarrays",
|
||||
"umghlrlose",
|
||||
|
@ -117,6 +117,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
|
||||
- LeetCode 5417. 定长子串中元音的最大数目 <https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/>
|
||||
|
||||
- [最长公共前缀](src/string/longest-common-prefix.js)
|
||||
|
||||
- LeetCode 14. 最长公共前缀 <https://leetcode-cn.com/problems/longest-common-prefix/>
|
||||
- LintCode 78. 最长公共前缀 <https://www.lintcode.com/problem/longest-common-prefix/description>
|
||||
|
||||
## 数组/队列/集合/映射
|
||||
|
||||
- [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js)
|
||||
|
27
src/string/longest-common-prefix.js
Normal file
27
src/string/longest-common-prefix.js
Normal file
@ -0,0 +1,27 @@
|
||||
const comp = (left, right, res) => {
|
||||
if (left.length > right.length) {
|
||||
[left, right] = [right, left]
|
||||
}
|
||||
|
||||
res = res || left
|
||||
while (right.indexOf(res) !== 0 && res.length > 0) {
|
||||
res = res.slice(0, res.length - 1)
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} strs
|
||||
* @return {string}
|
||||
*/
|
||||
export const longestCommonPrefix = function (strs) {
|
||||
if (strs.length < 2) return strs[0] || ''
|
||||
|
||||
let res = strs[0]
|
||||
for (let i = 1; i < strs.length; i++) {
|
||||
res = comp(res, strs[i])
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
8
test/string/longest-common-prefix.test.js
Normal file
8
test/string/longest-common-prefix.test.js
Normal file
@ -0,0 +1,8 @@
|
||||
import { longestCommonPrefix } from '../../src/string/longest-common-prefix'
|
||||
|
||||
test('最长公共前缀', () => {
|
||||
expect(longestCommonPrefix(['flower', 'flow', 'flight'])).toBe('fl')
|
||||
expect(longestCommonPrefix(['dog', 'racecar', 'car'])).toBe('')
|
||||
expect(longestCommonPrefix(['a'])).toBe('a')
|
||||
expect(longestCommonPrefix(['caa', '', 'a', 'acb'])).toBe('')
|
||||
})
|
Loading…
Reference in New Issue
Block a user