풀이
/**
* 387_FirstUniqueCharacterInAString.js
* Easy
* https://leetcode.com/problems/first-unique-character-in-a-string/
*/
var firstUniqChar = function(s) {
const strHash = {};
const sArr = s.split("");
sArr.forEach((char) => {
if (!strHash[char]) {
strHash[char] = 1;
} else {
strHash[char]++;
}
});
for (let i = 0; i < sArr.length; i++) {
if (strHash[sArr[i]] === 1) return i;
}
return -1;
};
해시 활용해서 해결했다. s 전체를 돌면서 해시 만들고, 다시 한 번 s 전체를 돌면서 확인하므로 O(2n) => O(n) 이다.
다른 사람 풀이
// 참조 - https://leetcode.com/problems/first-unique-character-in-a-string/discuss/369575/My-Javascript-Solution
var firstUniqChar = function(s) {
for(i=0; i<s.length; i++)
if(s.indexOf(s[i])===s.lastIndexOf(s[i])) return i
return -1
};
indexOf와 lastIndexOf 를 활용해서 두 값이 동일하면 앞 뒤에서 확인했을 때 하나밖에 존재하지 않는다는 것을 활용한 풀이다.
'알고리즘 > LeetCode' 카테고리의 다른 글
[Leetcode][자바스크립트][Easy] 242. Valid Anagram (0) | 2022.01.10 |
---|---|
[Leetcode][자바스크립트][Easy] 383. Ransom Note (0) | 2022.01.10 |
[Leetcode][자바스크립트][Easy] 566. Reshape the Matrix (0) | 2022.01.09 |
[Leetcode][자바스크립트][Easy] 121. Best Time to Buy and Sell Stock (0) | 2022.01.08 |
[Leetcode][자바스크립트][Easy] 350. Intersection of Two Arrays II (0) | 2022.01.08 |
댓글