标签:
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.
很简单一个题目,只是被自己蠢哭了。首先说一下回文构词法,回文构词法就是说所有字母出现的次数都是一样的。
自己用map实现了一个,做完之后,想想,这方法怎么这么眼熟,妈蛋,用容器不就可以了么!!!
class Solution { public: bool isAnagram(string s, string t) { int length=s.size(); if(length!=t.size()) return false; /*//法一
<span style="white-space:pre"> </span>map<char,int> tmp; for(int i=0;i<length;++i) { if(tmp.find(s[i])!=tmp.end()) tmp[s[i]]++; else tmp[s[i]]=1; } for(int j=0;j<length;++j) { if(tmp.find(t[j])==tmp.end()) return false; else tmp[t[j]]--; } for(map<char,int>::iterator iter=tmp.begin();iter!=tmp.end();++iter) { if(iter->second!=0) return false; } return true;
<span style="white-space:pre"> </span>//法一结束
<span style="white-space:pre"> </span>*/
<span style="white-space:pre"> </span>//法二: vector<int> tmp(26,0); for(int i=0;i<length;i++) { tmp[s[i]-'a']++; tmp[t[i]-'a']--; } for(int i=0;i<26;++i) { if(tmp[i]!=0) return false; } return true;
<span style="white-space:pre"> </span>//法二结束 } };
标签:
原文地址:http://blog.csdn.net/walker19900515/article/details/47297799