[每日LeetCode] 242. Valid Anagram

  |   0 评论   |   403 浏览

原文链接 [每日LeetCode] 242. Valid Anagram

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?


思路:本题要求验证两个字符串是不是同字母异序。可以使用map但是这里可以用cache数组来替代map功能,因为只涉及到小写字母且数量有限。首先判断两个字符串的长度是否相等,然后依次遍历s和t字符串并做好标记,最后判断cache中的数值即可。


C++代码

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

运行时间:8ms

运行内存:9.3M

评论

发表评论