难度级别:简单
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
输入: s = "anagram", t = "nagaram" 输出: true
输入: s = "rat", t = "car" 输出: false 说明: 你可以假设字符串只包含小写字母。
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
通过将2个字符串转为数组排序后,转为字符串进行比较
const isAnagram = (s,t) =>
s.length === t.length && [...s].sort().join("") === [...t].sort().join("")
通过数组创建哈希表,初始化长度为26,每个元素值为0。由于存在unicode的字符,使用String.prototype.codePointAt解析。首先遍历s字符串,对遍历到的字符在hashMap中进行+1,之后遍历t,对遍历到的元素进行-1,若遍历到的元素在hashMap中值小于0则输出false。
const isAnagram = (s,t) => {
if (s.length !== t.length) return false
const hashMap = new Array(26).fill(0)
for (let i = 0; i < s.length; i++)
hashMap[s.codePointAt(i) - 'a'.codePointAt(0)]++
for (let i = 0; i < t.length; ++i) {
hashMap[t.codePointAt(i) - 'a'.codePointAt(0)]--
if (hashMap[t.codePointAt(i) - 'a'.codePointAt(0)] < 0)
return false;
}
return true;
}
题目来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-anagram/
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。