当前位置:网站首页>leetode. 242. valid Letter heteronyms

leetode. 242. valid Letter heteronyms

2022-06-13 01:03:00 Didi dada

  1. Effective alphabetic words
    Given two strings s and t , Write a function to determine t Whether it is s Letter heteronym of .

Be careful : if s and t Each character in the has the same number of occurrences , said s and t They are mutually alphabetic words .

Example 1:

Input : s = “anagram”, t = “nagaram”
Output : true
Example 2:

Input : s = “rat”, t = “car”
Output : false

Tips :

1 <= s.length, t.length <= 5 * 104
s and t Only lowercase letters

Advanced : If the input string contains unicode What about characters ? Can you adjust your solution to deal with this situation ?242. Effective alphabetic words
Given two strings s and t , Write a function to determine t Whether it is s Letter heteronym of .

Be careful : if s and t Each character in the has the same number of occurrences , said s and t They are mutually alphabetic words .

Tips :
1 <= s.length, t.length <= 5 * 104
s and t Only lowercase letters

Advanced : If the input string contains unicode What about characters ? Can you adjust your solution to deal with this situation ?

Method 1 : By judging that the types and times of characters in two strings are equal

class Solution {
public:
    bool isAnagram(string s, string t) {
        int n1 = s.size();
        int n2 = t.size();
        if (n1!=n2) return false;
        unordered_map<char, int> m;
        for(auto it: s){
            m[it]++;
        }
        for(auto it: t){
            m[it]--;
            if(m[it]==0){
                m.erase(it);
            }
        }
        if (m.size()==0) return true;
        else return false;
    }
};

improvement : When two strings have the same length but are not heterotopic , Or the characters are inconsistent , Or the number of characters is wrong ( There must be a character that appears more times ), For both cases, we are traversing t when , perform m[it]--, Will appear m[it]<0 The situation of , Therefore, the above code can be changed to :

class Solution {
public:
    bool isAnagram(string s, string t) {
        int n1 = s.size();
        int n2 = t.size();
        if (n1!=n2) return false;
        unordered_map<char, int> m;
        for(auto it: s){
            m[it]++;
        }
        for(auto it: t){
            m[it]--;
            if(m[it]<0){
                return false;
            }
        }
        return true;
    }
};

Method 2 : Two strings are ectopic , Equivalent to after sorting , Two strings are equal

class Solution:
    import collections
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        s_list = list(s)
        t_list = list(t)
        s_list.sort()
        t_list.sort()
        return s_list == t_list
原网站

版权声明
本文为[Didi dada]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280556566745.html