LeetCodeOJ_242_Valid Anagram
来源:互联网 发布:mac综艺体字体下载 编辑:程序博客网 时间:2024/05/22 03:22
答题链接
题目:
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?
Tags Hash Table Sort
Similar Problems (M) Group Anagrams (E) Palindrome Permutation
分析:
先比较字符串s和字符串t的长度,若长度不等,直接返回false,若长度都为0,则返回true。
创建一个map,先存储s中出现的所有字母及其个数,然后,对t中的每个字母进行处理。针对t中的一个字母,如果map中存在该字母,则对应的个数减1,如果中途出现map中不存在的字母或者个数为负的情况,则终止程序,返回false,将t中所有字母处理完后,检查map中所有字母对应的个数是否为0,是则返回true,不是则返回false。
对于unicode字符,可将每一个字符转化为对应的编码数(一个整数),然后建立map< int,int>,以同样的方式进行处理。
代码:
class Solution {public: bool isAnagram(string s, string t) { int flag = 1; map<char,int> matchMap; map <char,int>::iterator it; int sizeS = s.size(); int sizeT = t.size(); if(sizeS!=sizeT) return false; if(sizeS==0&&sizeT==0) return true; for(int i=0;i<sizeS;++i) { it = matchMap.find(s[i]); if(it==matchMap.end()) matchMap.insert(map<char,int>::value_type(s[i],1)); else ++(*it).second; } for(int i=0;i<sizeT;++i) { it = matchMap.find(t[i]); if(it == matchMap.end()) { flag = 0; break; } else { --(*it).second; if((*it).second<0) { flag = 0; break; } } } if(flag) { for(it=matchMap.begin();it!=matchMap.end();++it) { if((*it).second!=0) { flag = 0; break; } } } if(flag) return true; else return false; }};
结果:
总结:
无
- LeetCodeOJ_242_Valid Anagram
- anagram
- Anagram
- Anagram
- Anagram
- Identify Anagram
- [Leetcode]Anagram
- poj-Anagram
- POJ1256 Anagram
- leetcode: anagram
- [LeetCode] Anagram
- poj1256 Anagram
- Valid Anagram
- Valid Anagram
- Valid Anagram
- Valid Anagram
- leetcode_Valid Anagram
- Valid Anagram
- 我的触摸屏制作”简史“1
- centos 编译安装python
- CSS学习<1>
- 日积月累
- iOS 跳转到 APP Store
- LeetCodeOJ_242_Valid Anagram
- php限制手机号码发送次数
- linux(raspberry) 安装配置 samba
- PHP 九种预定义超全局变量
- tp框架插入数据之add用法
- 日志记录组件[Log4net]
- 添加Swift到Objective-c失败
- ubuntu 15.10 必装软件
- C++格式化输出一:八进制,十进制,十六进制,二进制输出