Tuesday, August 18, 2015

Leetcode: Valid Anagram (hash table)(sort)

Problem:
https://leetcode.com/problems/valid-anagram/


----------------------------

1.  Using sort. I's easy but use more time.

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

};


2. using hash table:
Since all elements in string are composed with letters in lower case, we use a array with length of 26 to store the frequency of each letter for the first string;
for the second string, we minus the related frequency from the array and judge whether there are negative value in the array. Negative value means the two strings are not equal in terms of letters.


///////////////////////////////////////////////////////////////
// 12ms
class Solution {
public:
       bool isAnagram(string s, string t) {
              if (s.size() != t.size())return false;
              vector<int> tmp(26, 0);
              for (auto c : s){
                     tmp[c - 'a']++;
              }
              for (auto c : t){
                     if (--tmp[c - 'a']<0)return false;
              }
              return true;
       }
};









No comments:

Post a Comment