242.Valid Anagram

题目描述

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?

难度系数

Medium

解法一:排序后比较

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

解法二:记录每个字符串中字母出现的次数

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

 

猜你喜欢

转载自www.cnblogs.com/AntonioSu/p/12741562.html