Given two strings s and t, return true if t is an anagram of s, and false otherwise.
case1: Input: s = "anagram", t = "nagaram" Output: true
case2: Input: s = "rat", t = "car" Output: false
Hash를 이용한 접근법
- 주어진 길이를 비교하고 같지 않으면 false를 반환합니다.
- 빈 객체를 만들어 s문자열에 있는 모든 문자를 키로 저장합니다.
- 저장할 때 이미 존재하는 키가 있다면 value를 1씩 증가합니다.
- t문자열은 위에서 만든 객체에서 비교합니다.
- t문자열이 위의 객체의 키로 존재하지않으면 false를 리턴하고 존재하면 value를 1씩 감소합니다.
- 최종적으로 문자열의 길이와 문자가 모두 동일함을 의미함으로 true를 리턴합니다.
const validAnagram = (s, t) => {
if (s.length !== t.length) return false;
let hash = {};
for (let sChar of s) {
hash[sChar] = (hash[sChar] || 0) + 1;
}
for (let tChar of t) {
if (!hash[tChar]) return false;
hash[tChar]--;
}
return true;
}
'알고리즘' 카테고리의 다른 글
OddOccurrencesInArray_Codility (0) | 2022.02.16 |
---|---|
CyclicRotation_Codility (0) | 2022.02.15 |
Remove Nth Node From End of List - leetcode (0) | 2021.11.04 |
Single Number - XOR 연산자 (0) | 2021.09.27 |
Best Time to Buy and Sell Stock II (0) | 2021.09.09 |