码迷,mamicode.com
首页 > 其他好文 > 详细

242题——Valid Anagram (哈希表)

时间:2015-08-09 12:22:07      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

Valid Anagram

 Total Accepted: 9718 Total Submissions: 27840My Submissions

 

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.

 

Hide Tags
 Hash Table Sort
Hide Similar Problems
 (M) Anagrams
 
思路1:
这题采用两个长度为26的数组来存储从a到z的每个字母出现的次数,相当于将两个字符串都遍历一遍
然后将数组遍历一遍比较两个数组是否完全一样
若一样则true
否则false
 1 #include<iostream>
 2 #include<vector>
 3 #include<string>
 4 using namespace std;
 5 
 6 bool isAnagram(string s, string t) {
 7     vector<int> temp1(26,0);
 8     vector<int> temp2(26,0);
 9     for(auto i=s.begin();i!=s.end();i++)
10         temp1[(*i)-a]++;
11     for(auto j=t.begin();j!=t.end();j++)
12         temp2[(*j)-a]++;
13 
14     for(int i=0;i<26;i++)
15         if(temp1[i]!=temp2[i])
16             return false;
17     return true;
18 }
19 
20 int main()
21 {
22     string s="anagram";
23     string t="nagaram";
24     cout<<isAnagram(s,t)<<endl;
25     system("pause");
26 }

 这道题可以采用哈希表来做:

建立两个哈希表来存储:键为字符,值为个数

然后遍历哈希表,其实这种我做的明显比之前的方法要繁琐,而且非空间,还有要分别遍历两个哈希表。

 1 #include<iostream>
 2 #include<vector>
 3 #include<string>
 4 #include<map>
 5 using namespace std;
 6 
 7 bool isAnagram(string s, string t) {
 8     map<char,int> temp1;
 9     map<char,int> temp2;
10     for(auto i=s.begin();i!=s.end();i++)
11         temp1[*i]++;
12     for(auto i=t.begin();i!=t.end();i++)
13         temp2[*i]++;
14 
15     for(auto i=temp1.begin();i!=temp1.end();i++)
16         if(i->second!=temp2[i->first])
17             return false;
18 
19     for(auto i=temp2.begin();i!=temp2.end();i++)
20         if(i->second!=temp1[i->first])
21             return false;
22 
23     return true;
24 }
25 
26 int main()
27 {
28     string s="anagram";
29     string t="nagaram";
30     cout<<isAnagram(s,t)<<endl;
31     system("pause");
32 }

242题——Valid Anagram (哈希表)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4714689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!