Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅242. 有效的字母异位词 #44

Open
bazinga-web opened this issue Jun 29, 2020 · 3 comments
Open

✅242. 有效的字母异位词 #44

bazinga-web opened this issue Jun 29, 2020 · 3 comments

Comments

@bazinga-web
Copy link

242. 有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

@bazinga-web
Copy link
Author

解题思路:

  1. 首先判断两字符串长度是否一致,不一致返回false
  2. 创建map,分别遍历两字符串A,B。若map中不存在a则
    设置a的值为1,否则在值上+1。同理,若map中不存在b则
    设置b的值为-1,否则在其值上-1。最后遍历map中的每一个值
    若有一个不为0就返回false,否则返回true
/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function (s, t) {
    if (s.length !== t.length) return false;
    let map = new Map();
    for (let i = 0; i < s.length; i++) {
        let k = s[i],
            j = t[i];
        if (map.has(k)) {
            map.set(k, map.get(k) + 1);
        } else {
            map.set(k, 1);
        }

        if (map.has(j)) {
            map.set(j, map.get(j) - 1);
        } else {
            map.set(j, -1);
        }
    }

    for (const key of map) {
        if (key[1] !== 0) return false;
    }

    return true;
};

@bazinga-web
Copy link
Author

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
     if(s.length != t.length) return false;
     return  s.split('').sort().join('') == t.split('').sort().join('');
 }

@Ray-56
Copy link
Owner

Ray-56 commented Jun 30, 2020

解法一

哈希表

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
	if (s.length != t.length) return false;
	const map = new Map();
	for (let i = 0; i < s.length; i++) {
		const x = s[i];
		const y = t[i];
		if (map.has(x)) {
			map.set(x, map.get(x) + 1);
		} else {
			map.set(x, 1)
		}

		if (map.has(y)) {
			map.set(y, map.get(y) - 1);
		} else {
			map.set(y, -1)
		}
	}

	for (let [key, value] of map) {
		if (value !== 0) return false;
	}
	return true;
};

解法二

排序合并

var isAnagram = function(s, t) {
	if (s.length != t.length) return false;
	
	return s.split('').sort().join('') === t.split('').sort().join('')
};

@Ray-56 Ray-56 changed the title 242. 有效的字母异位词 ✅242. 有效的字母异位词 Jun 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants