leecode 解题总结:242. Valid Anagram

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
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<int , int> 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<int , int>::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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值