[路飞]_每天刷leetcode_48(有效的字母异位词 Valid Anagram)

107 阅读2分钟

「这是我参与2022首次更文挑战的第7天,活动详情查看:2022首次更文挑战

有效的字母异位词

LeetCode传送门 242. 有效的字母异位词

题目

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

注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。

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:

Input: s = "anagram", t = "nagaram"
Output: true

Input: s = "rat", t = "car"
Output: false

Constraints:

  • 1<=s.length,t.length<=51041 <= 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?


思考线


解题思路

首先看到这道题,我们要先确定如何才是字母异位?

是字符串中的每个字符出现的次数都相同即可。

那么很容易我就想到了使用hashMap 来记录这两个字符串中字符的次数

  • 若出现一个字符出现的次数不相等,这说明这两个字符串不是字母异位词
  • 若每一个字符出现的次数都相等,则说明这两个字符串是字母异位词

那么我们该如何在代码中实现呢?

我们可以设置两个map sHashtHash, 然后遍历st, 把字符全都扫码一遍。

最后我们比较每一个字符出现的次数即可。

代码如下:

function isAnagram(s: string, t: string): boolean {
    if (s.length !== t.length) return false;
    const len = s.length;
    const sHash = {};
    const tHash = {}
    for (let i = 0; i < len; i++) {
        if (!sHash[s[i]]) {
            sHash[s[i]] = 1;
        } else {
            sHash[s[i]] += 1;
        }
        if (!tHash[t[i]]) {
            tHash[t[i]] = 1;
        } else {
            tHash[t[i]] += 1;
        }
    }
    return Object.entries(sHash).every(([key, val]) => tHash[key] === val)
};

上面是我自己想出的解法,在解完后我看了LeetCode官网使用了只遍历其中一个字符串的想法。

其核心点是,for循环遍历其中的一个字符串把出现次数记录在hashMap中,然后遍历另一个字符串,每次把当前字符执行-1操作,若出现了小于0或者undefined的情况,则返回false,若到最后全部符合预期,则返回 true.

代码如下


function isAnagram(s: string, t: string): boolean {
    if (s.length !== t.length) return false;
    const len = s.length;
    const sHash = {};
    for (let i = 0; i < len; i++) {
        if (!sHash[s[i]]) {
            sHash[s[i]] = 1;
        } else {
            sHash[s[i]] += 1;
        }
    }
    for(let i = 0; i< len; i++) {
        if(sHash[t[i]] === undefined) return false;
        sHash[t[i]] --;
        if(sHash[t[i]] < 0) {
            return false
        }
    }
    return true;
};

时间复杂度分析

O(n): n为字符串的长度。

这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。