본문 바로가기

열정가득한 개발자의 이야기/Javascript Algorithm

leet code 387. First Unique Character in a String (javascript)

반응형

here is my answer

 

var firstUniqChar = function(s) {

//for getting the count of element, I think Map is necessary.
//so I declared the Map and used for loop for checking the count.

 

let a = new Map()
for(let i = 0; i < s.length; i++){
if(a.has(s[i])){
a.set(s[i], a.get(s[i])+1)
}else{
a.set(s[i], 1)
}
}

 

//after saving the count on Map,
//i need to find out the first factor which is on the first.
// so I use indexOf method, it is find the factor in first index.
//and also there is a possibility that doesn't have any 1 value,
//so I also use else statment, and block to occure the issue.
let result = 0
for(let i = 0; i< s.length; i++){
if(a.get(s[i]) === 1){
result = s.indexOf(s[i])
break
}else result = -1
}

 

return result

 

};
 
I know this code is not perfect, so I'm going to check others' code. Anyway, I solved one more algorithm by myself. That point really means a lot to me. I always struggle to improve myself. I think speed is not the most important thing; the most important thing is the direction.
 

 

 

+ I also change some code like this.

let result = 0
for(let i = 0; i< s.length; i++){
if(a.get(s[i]) === 1){
result = i
break
}else result= -1
}
return result

 

so there are some upgraded on memory and beats.

but not enough

반응형