LeetCode-Valid_Anagram

题目:

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.


翻译:

给定两个字符串 s  t, 写下一个函数来判断 是否为 的一个字谜。

举例,

s = "anagram", t = "nagaram", 返回真。

s = "rat", t = "car", 返回假。

注意:

你可以假设字符串中值包含小写字母。


思路:

首先要明确什么叫做作 t 是 s 的字谜。这里的字谜是要求字符串 t 的长度和 s 相等,并且,t 中含有和 s 中同样的字符,并且每一类字符的数量也要求相等。于是想到用 map 映射来解决,s 中出现的字符数量加一,同时若 t 中也出现同样的字符则作减一操作,最后,通过判断 map 中各字符的数量来判断 t 是否为 s 的字谜,若是,则 map 中所有字符数为0,返回 true,否则,返回 false。


C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

class Solution {
public:
	bool isAnagram(string s, string t) {
		if (s.size() != t.size())
			return false;
		unordered_map<char, int> m;
		for (int i = 0; i < s.size(); i++) {
			m[s[i]]++;
			m[t[i]]--;
		}
		for (int i = 0; i < s.size(); i++) {
			if (m[s[i]] != 0)
				return false;
		}
		return true;
	}
};
int main()
{
	Solution s;
	bool result;
	string p="ccac";
	string t = "acca";
	result = s.isAnagram(p, t);
	cout << result;
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值