从零开始的LC刷题(61): Valid Anagram

原题:

Given two strings s and , 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?

意思是看两个string中各个字母出现次数是否相同,用数组存储就行(哈希),结果:

Success

Runtime: 8 ms, faster than 98.42% of C++ online submissions for Valid Anagram.

Memory Usage: 9.4 MB, less than 50.10% of C++ online submissions for Valid Anagram.

代码:

class Solution {
public:
    bool isAnagram(string s, string t) {
        int hash[26]={0};
        string::iterator it;
        it=s.begin();
        while(it!=s.end()){
            hash[*it-97]++;
            it++;
        }
        it=t.begin();
        while(it!=t.end()){
            hash[*it-97]--;
            it++;
        }
        for(int i=0;i<26;i++){
            if(hash[i]!=0){return false;}
        }
        return true;
    }
};

solution还有sort的办法也不错,但是速度慢一些,结果:

Success

Runtime: 24 ms, faster than 31.61% of C++ online submissions for Valid Anagram.

Memory Usage: 9.6 MB, less than 16.28% of C++ online submissions for Valid Anagram.

代码:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size()!=t.size()){return false;}
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        int i=0;
        while(i

 

你可能感兴趣的:(LEETCODE,C++)