🌐 AI搜索 & 代理 主页
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@
* [CountVowels](String/CountVowels.js)
* [CreatePermutations](String/CreatePermutations.js)
* [DiceCoefficient](String/DiceCoefficient.js)
* [FirstUniqueCharacter](String/FirstUniqueCharacter.js)
* [FormatPhoneNumber](String/FormatPhoneNumber.js)
* [GenerateGUID](String/GenerateGUID.js)
* [HammingDistance](String/HammingDistance.js)
Expand Down
30 changes: 30 additions & 0 deletions String/FirstUniqueCharacter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* @function firstUniqChar
* @description Given a string str, find the first non-repeating character in it and return its index. If it does not exist, return -1.
* @param {String} str - The input string
* @return {Number} - The index of first unique character.
* @example firstUniqChar("javascript") => 0
* @example firstUniqChar("sesquipedalian") => 3
* @example firstUniqChar("aabb") => -1
*/

const firstUniqChar = (str) => {
if (typeof str !== 'string') {
throw new TypeError('Argument should be string')
}
const count = new Map()

for (const char of str) {
if (!count[char]) {
count[char] = 1
} else {
count[char]++
}
}
for (let i = 0; i < str.length; i++) {
if (count[str[i]] === 1) return i
}
return -1
}

export { firstUniqChar }
9 changes: 9 additions & 0 deletions String/test/FirstUniqueCharacter.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { firstUniqChar } from '../FirstUniqueCharacter'

describe('firstUniqChar', () => {
it('locates the index of first unique character in the string', () => {
expect(firstUniqChar('javascript')).toEqual(0)
expect(firstUniqChar('sesquipedalian')).toEqual(3)
expect(firstUniqChar('aabb')).toEqual(-1)
})
})