标签:
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.
Analyse: This question actually asks us to judge whether two strings have the same alphabats, i.e. they have same alphabats set and each alphabat has the occurence.
1. judge equality after sorting.
Runtime: 76ms.
1 class Solution { 2 public: 3 bool isAnagram(string s, string t) { 4 sort(s.begin(), s.end()); 5 sort(t.begin(), t.end()); 6 return s == t; 7 } 8 };
2. Count the occurence of each alphabat and compare the occurence.
Runtime: 12ms.
1 class Solution { 2 public: 3 bool isAnagram(string s, string t) { 4 if(s.length() != t.length()) return false; 5 6 int arrS[26] = {0}, arrT[26] = {0}; 7 for(int i = 0; i < s.length(); i++){ 8 arrS[s[i] - ‘a‘]++; 9 arrT[t[i] - ‘a‘]++; 10 } 11 for(int j = 0; j < 26; j++){ 12 if(arrS[j] != arrT[j]) return false; 13 } 14 return true; 15 } 16 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4696850.html