728x90
[Javascript] (LeetCode) 387. First Unique Character in a String (Easy)
💡 구글에 Javascript 풀이가 많이 없거나, 배운 점이 있으면 포스팅합니다.
내 풀이
/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function(s) {
let map = new Map();
for (let i = 0; i < s.length; i++) {
map.set(s[i], (map.get(s[i]) || 0) + 1);
}
let answerChar = '';
for (let [k, v] of map) {
if (v === 1) {
answerChar = k;
break;
}
}
for (let i = 0; i < s.length; i++) {
if (s[i] === answerChar) {
return i;
}
}
return -1;
};
다른 풀이
/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function(s) {
for (let i = 0; i < s.length; i++) {
if (s.indexOf(s[i]) === s.lastIndexOf(s[i])) {
return i;
}
}
return -1;
};
'Coding Test > LeetCode' 카테고리의 다른 글
[Javascript] (LeetCode) 28. Implement strStr() (Easy) (0) | 2022.08.03 |
---|---|
[Javascript] (LeetCode) 8. String to Integer (atoi) (Medium) (0) | 2022.08.02 |
[Javascript] (LeetCode) 125. Valid Palindrome (Easy) (0) | 2022.07.29 |
[Javascript] (LeetCode) 242. Valid Anagram (Easy) (0) | 2022.07.28 |
[Javascript] (LeetCode) 7. Reverse Integer (Medium) (0) | 2022.07.25 |
[Javascript] (LeetCode)136. Single Number (Easy) (0) | 2022.07.25 |
[Javascript] (LeetCode) 217. Contains Duplicate (Easy) (0) | 2022.07.24 |
[Javascript] (LeetCode)122. Best Time to Buy and Sell Stock II (Medium) (0) | 2022.07.22 |
댓글