diff --git a/.vscode/settings.json b/.vscode/settings.json index 8167afe..de519b9 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -8,6 +8,7 @@ "lcci", "lcof", "lcov", + "leetcode", "lrloseumgh", "mincost", "nums", diff --git a/README.md b/README.md index 8514e55..ba1cc1c 100644 --- a/README.md +++ b/README.md @@ -287,6 +287,12 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LintCode 685. 数据流中第一个唯一的数字 +- [第一个只出现一次的字符](src/array/first-unique-character-in-a-string.js) + + - LeetCode 面试题50. 第一个只出现一次的字符 + - LeetCode 387. 字符串中的第一个唯一字符 + - LintCode 209. 第一个只出现一次的字符 + ## 栈 - [最大矩阵](src/stack/maximal-rectangle.js) diff --git a/src/array/first-unique-character-in-a-string.js b/src/array/first-unique-character-in-a-string.js new file mode 100644 index 0000000..9516551 --- /dev/null +++ b/src/array/first-unique-character-in-a-string.js @@ -0,0 +1,18 @@ +/** + * @param {string} s + * @return {character} + */ +export const firstUniqChar = function (s) { + const due = new Set() + const queue = new Set() + for (const n of s) { + if (queue.has(n)) { + queue.delete(n) + due.add(n) + } else if (!due.has(n)) { + queue.add(n) + } + } + + return Array.from(queue)[0] || ' ' +} diff --git a/test/array/first-unique-character-in-a-string.test.js b/test/array/first-unique-character-in-a-string.test.js new file mode 100644 index 0000000..edd327e --- /dev/null +++ b/test/array/first-unique-character-in-a-string.test.js @@ -0,0 +1,5 @@ +import { firstUniqChar } from '../../src/array/first-unique-character-in-a-string' + +test('第一个只出现一次的字符', () => { + expect(firstUniqChar('leetcode')).toBe('l') +})