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

Leetcode Valid Anagram

时间:2015-11-12 17:48:12      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

 1 #include<map>
 2 #include<string>
 3 #include<iterator>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     bool isAnagram(string s, string t) {
 9         string temp1,temp2,temp3;
10         int c1,c2;
11         map<string,int> dictionary1,dictionary2;
12         for(int i=0;i<s.length();i++) {
13             temp1=s[i];
14             ++dictionary1[temp1];}
15         for(int j=0;j<t.length();j++) {
16             temp2=t[j];
17             ++dictionary2[temp2];}
18             
19         if(dictionary1.size()!=dictionary2.size()) return false;
20         for(auto i=dictionary1.begin();i!=dictionary1.end();i++)
21         {
22             c1=(*i).second;
23             temp3=(*i).first;
24             c2=dictionary2[temp3];
25             if(c1!=c2) return false;
26         }
27         return true;    
28         
29     }
30 };

 


 

 tips:

 string当然不一定要初始化。

 C++中没有直接判断map是否相等的函数;

 map中有iterator;

 map中的元素是pair,我们可以用first来取关键字,second来取值;

Leetcode Valid Anagram

标签:

原文地址:http://www.cnblogs.com/LUO77/p/4959663.html

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