当前位置: 面试刷题>> 两个字符串是变位词 (经典算法题500道)


题目描述补充

题目:给定两个字符串 s1s2,判断它们是否是变位词(Anagram)。变位词是指两个字符串包含相同数量和种类的字符,但字符的顺序可能不同。

示例

  • 输入:s1 = "listen"s2 = "silent"

  • 输出:true,因为 s1s2 包含相同数量和种类的字符。

  • 输入:s1 = "hello"s2 = "world"

  • 输出:false,因为 s1s2 包含的字符种类和数量不同。

注意

  • 你可以假设字符串只包含小写字母。
  • 字符串的长度可能不同,如果长度不同,则它们一定不是变位词。

PHP 示例代码

function isAnagram($s1, $s2) {
    // 如果长度不同,则不是变位词
    if (strlen($s1) !== strlen($s2)) {
        return false;
    }

    // 统计每个字符出现的次数
    $count = array_fill(0, 26, 0);
    for ($i = 0; $i < strlen($s1); $i++) {
        $count[ord($s1[$i]) - ord('a')]++;
        $count[ord($s2[$i]) - ord('a')]--;
    }

    // 检查所有字符计数是否归零
    foreach ($count as $c) {
        if ($c !== 0) {
            return false;
        }
    }

    return true;
}

// 测试示例
echo isAnagram("listen", "silent") ? "true" : "false"; // 输出 true
echo "\n";
echo isAnagram("hello", "world") ? "true" : "false"; // 输出 false

Python 示例代码

def isAnagram(s1: str, s2: str) -> bool:
    # 如果长度不同,则不是变位词
    if len(s1) != len(s2):
        return False

    # 使用字典统计字符出现次数
    count = {}
    for char in s1:
        if char in count:
            count[char] += 1
        else:
            count[char] = 1

    for char in s2:
        if char in count:
            count[char] -= 1
        else:
            return False

    # 检查所有字符计数是否归零
    for c in count.values():
        if c != 0:
            return False

    return True

# 测试示例
print(isAnagram("listen", "silent")) # 输出 True
print(isAnagram("hello", "world")) # 输出 False

JavaScript 示例代码

function isAnagram(s1, s2) {
    // 如果长度不同,则不是变位词
    if (s1.length !== s2.length) {
        return false;
    }

    // 使用数组统计字符出现次数(ASCII码 - 'a'.charCodeAt(0) 作为索引)
    const count = new Array(26).fill(0);
    for (let i = 0; i < s1.length; i++) {
        const index1 = s1.charCodeAt(i) - 'a'.charCodeAt(0);
        const index2 = s2.charCodeAt(i) - 'a'.charCodeAt(0);
        count[index1]++;
        count[index2]--;
    }

    // 检查所有字符计数是否归零
    for (let c of count) {
        if (c !== 0) {
            return false;
        }
    }

    return true;
}

// 测试示例
console.log(isAnagram("listen", "silent")); // 输出 true
console.log(isAnagram("hello", "world")); // 输出 false

码小课提示: 码小课网站中有更多关于算法和数据结构的相关内容分享,涵盖多种编程语言实现,欢迎大家学习交流。

推荐面试题