【leetcode】242. Valid Anagram

来源:互联网 发布:淘宝团队架构 编辑:程序博客网 时间:2024/06/05 09:25

一、题目描述

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?


题目大意是给两个字符串,两个字符串中的字母一样,且字母的出现次数也一样。


自己写的c++代码(140ms)

 思路:首先,字符串长度不一样的肯定返回false,然后,建立map将两个字符串中的字母和出现的次数对应起来。然后遍历每个字母查看出现的次数。

#include<map>#include<iostream>#include<string>using namespace std;class Solution {public:    bool isAnagram(string s, string t) {        if(s.size() != t.size())            return false;        else{            int len = s.size();            map<char, int> m1;            map<char, int> m2;            for(int i=0; i<len; i++){                if(m1[s[i]]>0)                    m1[s[i]] ++;                else                    m1[s[i]]=1;                                    if(m2[t[i]] > 0)                    m2[t[i]] ++;                else                    m2[t[i]]=1;            }            for(int i=0;i<len;i++){                if(m1[s[i]] != m2[s[i]])                    return false;            }            return true;        }//else

看了一下discuss,大神们还给出了很多优化的方法

代码1(36ms)

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


代码2(12ms)因为只有小写字母,因此代码还可进一步优化成:


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


代码3(76ms)先将两个字符串排序,排序完之后必然相等


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


python代码:

def isAnagram1(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 == dic2def isAnagram2(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 == dic2def isAnagram3(self, s, t):    return sorted(s) == sorted(t)



0 0