leecode 解题总结:242. Valid Anagram

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
/*
问题:
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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

分析:其实就是判断一个单词是不是另一个单词的变位词。
可以直接排序后比较是否相等

或者直接统计排序更好,时间复杂度为O(n),然后每次比较次数是否相同

输入
anagram nagaram
rat car
输出:
true
false

关键:
1 用map做统计排序,碰到 s中出现的某个字符就累加,碰到t中出现的字符就累减,
检查map中所有元素出现次数必须为0,则就是正确的
*/

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.empty() && t.empty())
		{
			return true;
		}
		else if(s.empty() || t.empty())
		{
			return false;
		}
		if(s.size() != t.size())
		{
			return false;
		}
		int size1 = s.size();
		//碰到 s中出现的某个字符就累加,碰到t中出现的字符就累减
		unordered_map valueToTimes1;
		for(int i = 0 ; i < size1 ; i++)
		{
			if(valueToTimes1.find(s.at(i)) != valueToTimes1.end())
			{
				valueToTimes1[s.at(i)]++;
			}
			else
			{
				valueToTimes1[s.at(i)] = 1;
			}
			if(valueToTimes1.find(t.at(i)) != valueToTimes1.end())
			{
				valueToTimes1[t.at(i)]--;
			}
			else
			{
				valueToTimes1[t.at(i)] = -1;
			}			
		}
		//检查map中所有元素出现次数必须为0
		for(unordered_map::iterator it = valueToTimes1.begin() ; it != valueToTimes1.end() ; it++)
		{
			if(it->second != 0)
			{
				return false;
			}
		}
		return true;
    }

    bool isAnagram2(string s, string t) {
        if(s.empty() && t.empty())
		{
			return true;
		}
		else if(s.empty() || t.empty())
		{
			return false;
		}
		if(s.size() != t.size())
		{
			return false;
		}
		sort(s.begin() , s.end());
		sort(t.begin() , t.end());
		return s == t ;
    }
};

void process()
{
	 Solution solution;
	 string str1;
	 string str2;
	 while(cin >> str1 >> str2 )
	 {
		 bool result = solution.isAnagram(str1 , str2);
		 if(result)
		 {
			 cout << "true" << endl;
		 }
		 else
		 {
			 cout << "false" << endl;
		 }
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


你可能感兴趣的:(leecode)