Valid Anagram
Description
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?
Solution(javascript)
const wordPattern = (pattern, str) => {
const patternMap = Array.prototype.reduce.call(pattern, (map, c, index) => {
if (map[c]) {
map[c]++
} else {
map[c] = 1
}
return map
}, {})
const wordArr = str.split(' ')
if (wordArr.length !== pattern.length) {
return false
}
const wordMap = wordArr.reduce((map, word) => {
if (map[word]) {
map[word]++
} else {
map[word] = 1
}
return map
}, {})
for (let i = 0; i < pattern.length; i++) {
if (patternMap[pattern[i]] !== wordMap[wordArr[i]]) {
return false
}
}
return true
}
const isAnagram = (s, t) => {
const map = {}
if (s.length !== t.length) {
return false
}
for (c of s) {
if (map[c]) {
map[c]++
} else {
map[c] = 1
}
}
for (c of t) {
if (!map[c]) {
return false
}
map[c]--
}
for (c of s) {
if (map[c] !== 0) {
return false
}
}
return true
}