- Valid Anagram
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
**Input:** s = "anagram", t = "nagaram"
**Output:** true
Example 2:
**Input:** s = "rat", t = "car"
**Output:** false
Constraints:
1 <= s.length, t.length <= 5 * 10^4
s
andt
consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Idea
方法1: 暴露排序比较,O(nlogN)
方法2: 使用map统计字符个数,如果是异为词,则同一个字符 加/减 后为0 ,O(n)
JavaScript Solution
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
const comp = (a,b)=>a.charCodeAt(0)-b.charCodeAt(0)
const sort = (str) => str.split("").sort(comp).join("")
return sort(s)===sort(t)
};
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
const map = {}
for( let a of s ){
if(!map[a]){
map[a] = 1;
}else{
map[a] ++;
}
}
for( let a of t ){
if(!map[a]){
return false
}else{
map[a] --;
if(!map[a]){
delete map[a]
}
}
}
return !Object.keys(map).length;
};
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 【LeetCode 0242】【Map/排序】有效的异位词
发表评论 取消回复