Skip to content

Latest commit

 

History

History
149 lines (118 loc) · 3.16 KB

File metadata and controls

149 lines (118 loc) · 3.16 KB

English Version

题目描述

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

示例 1:

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

示例 2:

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

说明:
你可以假设字符串只包含小写字母。

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

解法

哈希表解决。

Python3

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        n = len(s)
        chars = [0] * 26
        for i in range(n):
            chars[ord(s[i]) - ord('a')] += 1
            chars[ord(t[i]) - ord('a')] -= 1
        for i in range(26):
            if chars[i] != 0:
                return False
        return True

Java

class Solution {
    public boolean isAnagram(String s, String t) {
        int n;
        if ((n = s.length()) != t.length()) {
            return false;
        }
        int[] chars = new int[26];
        for (int i = 0; i < n; ++i) {
            ++chars[s.charAt(i) - 'a'];
            --chars[t.charAt(i) - 'a'];
        }
        for (int i = 0; i < 26; ++i) {
            if (chars[i] != 0) {
                return false;
            }
        }
        return true;
    }
}

TypeScript

function isAnagram(s: string, t: string): boolean {
    if (s.length != t.length) return false;
    let record = new Array(26).fill(0);
    let base = 'a'.charCodeAt(0);
    for (let i = 0; i < s.length; ++i) {
        ++record[s.charCodeAt(i) - base];
        --record[t.charCodeAt(i) - base];
    }
    return record.every(v => v == 0);
};

C++

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) {
            return false;
        }
        vector<int> chars(26, 0);
        for (int i = 0, n = s.size(); i < n; ++i) {
            ++chars[s[i] - 'a'];
            --chars[t[i] - 'a'];
        }
        for (int i = 0; i < 26; ++i) {
            if (chars[i] != 0) {
                return false;
            }
        }
        return true;
    }
};

Go

func isAnagram(s string, t string) bool {
	if len(s) != len(t) {
		return false
	}
	var chars [26]int
	for i := 0; i < len(s); i++ {
		chars[s[i]-'a']++
		chars[t[i]-'a']--
	}
	for i := 0; i < 26; i++ {
		if chars[i] != 0 {
			return false
		}
	}
	return true
}

...