242. Valid Anagram

本文介绍了一种通过比较两个字符串是否为异位构词的方法。利用排序或哈希表统计字符频次来高效判断两个字符串是否由相同字符组成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

题目链接:


思路分析

给两个string,判断这两个string是否是异位构词,即用相同的字母打乱顺序重新产生一个新词。

因为使用的字母相同,不同字母的个数也相同,可以将两string排序,判断是否相同。

代码
class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s == t;
    }
};

时间复杂度: O(n2) // Bubble sorting
空间复杂度: O(1)


反思

可以使用hash table来提升速度。使用unordered_map,建立丛char到int的一个映射,就可以轻松统计每个字符出现的次数了。

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length() != t.length())
            return false;
        unordered_map<char, int> count;
        for (int i = 0; i < s.length(); i++){
            count[s[i]]++;
            count[t[i]]--;
        }
        for (auto i:count){
            if (i.second)
                return false;
        }
        return true;
    }
};

在开始条件下,如果只有26个小写字母,可以使用数组来模拟一个hash table。

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length() != t.length()) return false;
        int n = s.length();
        int counts[26] = {0};
        for (int i = 0; i < n; i++) { 
            counts[s[i] - 'a']++;
            counts[t[i] - 'a']--;
        }
        for (int i = 0; i < 26; i++)
            if (counts[i]) return false;
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值