Leetcode [Easy] 242 - Valid Anagram
LeetCode 242
Valid Anagram
문제
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
나의 코드
function isAnagram(s: string, t: string): boolean {
let answer: boolean;
const map = new Map<string, number>();
for (let i = 0; i < s.length; i++) {
const temp: number | undefined = map.get(s[i]);
if (temp === undefined) map.set(s[i], 1);
else map.set(s[i], temp + 1);
}
for (let i = 0; i < t.length; i++) {
const temp: number | undefined = map.get(t[i]);
if (!temp) return false;
else {
if (temp - 1) map.set(t[i], temp - 1);
else map.delete(t[i]);
}
}
return map.size === 0;
}
참고 코드
배운점
Subscribe via RSS