forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstUniqueCharacter.js
More file actions
Latest commit
30 lines (27 loc) · 797 Bytes
/
Copy pathFirstUniqueCharacter.js
File metadata and controls
30 lines (27 loc) · 797 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
*/
constfirstUniqChar=(str)=>{
if(typeofstr!=='string'){
thrownewTypeError('Argument should be string')
}
constcount=newMap()
for(constcharofstr){
if(!count[char]){
count[char]=1
}else{
count[char]++
}
}
for(leti=0;i<str.length;i++){
if(count[str[i]]===1)returni
}
return-1
}
export{firstUniqChar}