Skip to content

Latest commit

 

History

History
executable file
·
60 lines (43 loc) · 2.71 KB

242. Valid Anagram.md

File metadata and controls

executable file
·
60 lines (43 loc) · 2.71 KB

#

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 ##(一)题目

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.

Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?

##(二)解题

题目大意:给定两个字符串s和t,判断t是不是s的有效字谜

解题思路:有效字谜是指t是由s中的字符改变相对位置后组成的字符串。

84ms解题版本:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.length()!=t.length()) return false;//长度不等,直接返回false
        sort(s.begin(),s.end());//排序
        sort(t.begin(),t.end());
        return s==t?true:false;//判断是否相等
    }
};

12ms的版本:

用哈希表,首先遍历s,记录每个字符出现的次数,然后遍历t,出现某个字符就次数就减1,判断最后的次数是否都为0

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