Leetcode [Easy] 387 - First Unique Character in a String
LeetCode 387
First Unique Character in a String
문제
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
Note: You may assume the string contains only lowercase English letters.
나의 코드
function firstUniqChar(s: string): number {
const memo = new Map<string, number>();
for (let i = 0; i < s.length; i++) {
const temp: number | undefined = memo.get(s[i]);
if (temp === undefined) memo.set(s[i], 1);
if (typeof temp === "number") memo.set(s[i], temp + 1);
}
for (let i = 0; i < s.length; i++) {
if (memo.get(s[i]) === 1) return i;
}
return -1;
}
참고 코드
// 1
// 비슷한 풀이
var firstUniqChar = function (s) {
let map = {};
for (let char of s) {
map[char] ? map[char]++ : (map[char] = 1);
}
for (let i = 0; i < s.length; i++) {
if (map[s[i]] === 1) return i;
}
return -1;
};
// 2
// 의외로 빠름
// O(N^2) 이라고 생각했는데...
var firstUniqChar = function (s) {
for (i = 0; i < s.length; i++)
if (s.indexOf(s[i]) === s.lastIndexOf(s[i])) return i;
return -1;
};
배운점
map[char] ? map[char]++ : map[char] = 1
참고 (assign 식 외에도 turnary 사용하는 방법)String.prototype.lastIndexOf()
Subscribe via RSS