<LeetCode OJ> 242. Valid Anagram

本文介绍了一种高效的方法来判断两个字符串是否通过移位形成同构关系,包括排序法、数组计数法和哈希映射法,适用于包含小写字母的字符串判断。

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

242. Valid Anagram

Total Accepted: 49981  Total Submissions: 125435  Difficulty: Easy

给定两个字符串s和t,写一个函数判断是否t是通过移位得到的s

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.举例:t中的前两个字符互移位将得到s
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?



分析:

简单模拟思想,如果只是简单的发生了移位,显然排序后应该是一样的!否则不是!

class Solution {
public:
    bool isAnagram(string s, string t) {
            if(s.size()!=t.size())
                return false;
            sort(s.begin(),s.end());
            sort(t.begin(),t.end());
            return s==t;
    }
};

学习于讨论区

第二种方法:设计数组统计出现次数

思路首先:s和t必须拥有相同个数的字符,并且所有字符必须相同
申请一个数组vecnt来统计字符出现的次数,s中出现的字符则增加对应数组位置的值,t则减少
如果t中的某个字符没有和s出现相同的次数,那么vecnt中对应位置的值必不为0

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.empty() && t.empty())
            return true;
        if(s.size() != t.size()) 
            return false;
    
       vector<int> vecnt(26);
        for(int i=0;i<s.size();i++){
            vecnt[s[i]-'a']++;
            vecnt[t[i]-'a']--;//遍历完数组,如果移位,应该所有值都为0
        }
    
        for(int i=0;i<26;i++)
            if(vecnt[i] != 0) 
                return false;
        
        return true;
    }
};

学习于讨论区

第三种方法:多关键值哈希map(可统计字符出现次数)

//思路首先:
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length() != t.length()) 
            return false;
        unordered_map<char, int> countsmap;
        for (int i = 0; i < s.size(); i++) {
            countsmap[s[i]]++;
            countsmap[t[i]]--;
        }
        unordered_map<char,int>::iterator ite;
        for(ite=countsmap.begin();ite!=countsmap.end();ite++)
            if(ite->second) 
                return false;
        
        return true;
    }
};


原文:

Hash Table

This idea uses a hash table to record the times of appearances of each letter in the two stringss and t. For each letter in s, it increases the counter by 1 while for each letter in t, it decreases the counter by 1. Finally, all the counters will be 0 if they two are anagrams of each other.

The first implementation uses the built-in unordered_map and takes 36 ms.

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

Since the problem statement says that "the string contains only lowercase alphabets", we can simply use an array to simulate the unordered_map and speed up the code. The following implementation takes 12 ms.

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;
    }
};

Sorting

For two anagrams, once they are sorted in a fixed order, they will become the same. This code is much shorter (this idea can be done in just 1 line using Python as here). However, it takes much longer time --- 76 ms in C++.

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

注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.youkuaiyun.com/ebowtang/article/details/50493241

原作者博客:http://blog.youkuaiyun.com/ebowtang


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值