242.Valid Anagram

Title description

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

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: 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?

degree of difficulty

Medium

Solution 1: Compare after sorting

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

 

Solution 2: record the number of letters in each string

class Solution {
public:
    bool isAnagram(string s, string t) {
        int s_alpha[26]={0};
        int t_alpha[26]={0};
        if(s.size()!=t.size())
            return false;
        for (int i = 0; i < s.size(); ++i) {
            s_alpha[s[i]-'a']++;
            t_alpha[t[i]-'a']++;
        }
        for (int j = 0; j < 26; ++j) {
            if(s_alpha[j]!=t_alpha[j])
                return false;
        }
        return true;
    }
};

 

 

Guess you like

Origin www.cnblogs.com/AntonioSu/p/12741562.html
242