1. 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 and t 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;
};

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部