LeetCode-242——有效的字母异位词(Java、Python)

题目

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

​ 示例:

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

输入: s = "rat", t = "car"
输出: false

解法

​ 这里提供三种解法

直接排序

​ 因为大部分语言中都自带排序函数,我们可以直接把两个字符串进行排序,因为如果两个字符串互为字母异位词的话,那么他们所包含的字母及每个字母的数量就是一致的,代码很简洁,使用 Python 的话只有两行

Python 代码

def isAnagram(self, s, t):
    return sorted(s) == sorted(t)

使用 map 记住每个字母的数量

​ 我们也可以利用 map 键值对的特性,使用两个 map 来存储每个字符串中的每一个字母出现的次数,最后直接比较这两个 map 是否相等即可,代码使用的是 Python 中的字典

Python 代码

def isAnagram(self, s, t):
    dic1, dic2 = {}, {}
    for item in s:
        dic1[item] = dic1.get(item, 0) + 1
    for item in t:
        dic2[item] = dic2.get(item, 0) + 1
    return dic1 == dic2

使用长度为 26 的数组计数

​ 题目给出了两个字符串中的字符均为小写,我们可以直接初始化两个长为 26,初始值都为 0 的数组,然后遍历两个字符串来给字符串中的字符进行计数,最后比较数组是否相等

Java 代码

public boolean isAnagram(String s, String t) {
    int[] a = new int[26];
    int[] b = new int[26];
    for (char c : s.toCharArray()) {
        a[(int)c - (int)('a')] += 1;
    }
    for (char c : t.toCharArray()) {
        b[(int)c - (int)('a')] += 1;
    }
    return Arrays.equals(a, b);
}

Python 代码

def isAnagram(self, s, t):
    dic1, dic2 = [0] * 26, [0] * 26
    for item in s:
        dic1[ord(item) - ord('a')] += 1
    for item in t:
        dic2[ord(item) - ord('a')] += 1
    return dic1 == dic2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章