问题描述

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.

异位构词判断。判断两个字符串是不是只是异位构词,也就是只有字母的顺序不一样,但每字符的种类和对应的数量一样。假设只有26个小写字母。

分析

使用一个长度为26的数组进行字母的计数。对于第一个字符串进行加1操作,也就是每出现一个字母,就在对应的字母位加1;对于第二个字符串进行减1操作,每出现一个字母就在相应的字母位减1。最后判断整个计数数组的每个数是不是都为0,是则返回true。

代码

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