Valid Anagram Solutions in C++
Number 242
Difficulty Easy
Acceptance 56.9%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/valid-anagram/// Author : Hao Chen// Date : 2015-08-16class Solution {public://stupid way - but easy to understand - 76msbool isAnagram01(string s, string t) {sort(s.begin(), s.end());sort(t.begin(), t.end());return s == t;}//using a map to count every chars in the string.bool isAnagram02(string s, string t) {int map[26] ={0} ; //only lowercase alphabets//memset(map, 0, sizeof(map));// count each char for sfor (int i=0; i<s.size(); i++) {map[s[i]-'a']++;}// decrease the count for tfor (int i=0; i<t.size(); i++) {map[t[i]-'a']--;}//if all alphabets is zero, then they are anagramfor (int i=0; i<sizeof(map)/sizeof(map[0]); i++) {if (map[i]!=0) return false;}return true;}bool isAnagram(string s, string t) {return isAnagram02(s,t); //12msreturn isAnagram01(s,t); //76ms}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/valid-anagram//// Author : liuyubobobo/// Time : 2018-08-13#include <iostream>using namespace std;/// Sorting/// Time Complexity: O(nlogn)/// Space Complexity: O(1)class Solution {public:bool isAnagram(string s, string t) {sort(s.begin(), s.end());sort(t.begin(), t.end());return s == t;}};int main() {cout << Solution().isAnagram("anagram", "nagaram") << endl;cout << Solution().isAnagram("rat", "car") << endl;cout << Solution().isAnagram("ab", "a") << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/valid-anagram//// Author : liuyubobobo/// Time : 2017-01-17#include <iostream>using namespace std;/// Using Hashtable/// Time Complexity: O(n)/// Space Complexity: O(26)class Solution {public:bool isAnagram(string s, string t) {if( s.size() != t.size() )return false;int freq[26] = {0};for( int i = 0 ; i < s.size() ; i ++ )freq[s[i]-'a'] ++;for( int i = 0 ; i < t.size() ; i ++ ){freq[t[i]-'a'] --;if( freq[t[i]-'a'] < 0 )return false;}return true;}};int main() {cout << Solution().isAnagram("anagram", "nagaram") << endl;cout << Solution().isAnagram("rat", "car") << endl;cout << Solution().isAnagram("ab", "a") << endl;return 0;}