From 8ca4a189f8a23d46b9c118ef61e019fafdaa85d3 Mon Sep 17 00:00:00 2001 From: yige Date: Sun, 24 May 2020 19:42:58 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E6=9C=80=E9=95=BF=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E5=89=8D=E7=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/settings.json | 2 ++ README.md | 5 +++++ src/string/longest-common-prefix.js | 27 +++++++++++++++++++++++ test/string/longest-common-prefix.test.js | 8 +++++++ 4 files changed, 42 insertions(+) create mode 100644 src/string/longest-common-prefix.js create mode 100644 test/string/longest-common-prefix.test.js diff --git a/.vscode/settings.json b/.vscode/settings.json index 0f9d0d1..8f2ef8c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -26,6 +26,8 @@ "preorder", "pwwkew", "qian", + "racecar", + "strs", "subarray", "subarrays", "umghlrlose", diff --git a/README.md b/README.md index 7a3a3fb..23ba1a0 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 5417. 定长子串中元音的最大数目 +- [最长公共前缀](src/string/longest-common-prefix.js) + + - LeetCode 14. 最长公共前缀 + - LintCode 78. 最长公共前缀 + ## 数组/队列/集合/映射 - [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js) diff --git a/src/string/longest-common-prefix.js b/src/string/longest-common-prefix.js new file mode 100644 index 0000000..7f61c10 --- /dev/null +++ b/src/string/longest-common-prefix.js @@ -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 +} diff --git a/test/string/longest-common-prefix.test.js b/test/string/longest-common-prefix.test.js new file mode 100644 index 0000000..cbcb8d5 --- /dev/null +++ b/test/string/longest-common-prefix.test.js @@ -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('') +})