[leetcode] 242.Valid Anagram
2015-08-02 10:55
363 查看
题目:
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,判断T是不是S的字符经过调整位置得到。
思路:
只需要记录两个字符串是否出现了一样多的字符,每个字符是否出现的次数相同即可。使用数组当做hash来记录字符出现的次数。
以上。
代码如下:
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,判断T是不是S的字符经过调整位置得到。
思路:
只需要记录两个字符串是否出现了一样多的字符,每个字符是否出现的次数相同即可。使用数组当做hash来记录字符出现的次数。
以上。
代码如下:
class Solution { public: bool isAnagram(string s, string t) { if(s.length() != t.length())return false; else if(s.length() == 0)return true; int dict[256]; memset(dict, 0, sizeof(dict)); int count = 0; for(auto c : s) { count += (dict[c] == 0)? 1 : 0; dict[c]++; } for(auto c : t) { dict[c]--; count -= (dict[c] == 0)? 1: 0; } return (count == 0); } };
相关文章推荐
- 每一个优秀的人,都有一段沉默的时光,是那一段时光,不抱怨不诉苦,最后渡过了这段感动自己的日子
- Java之反射机制【入门版(2)】
- Selenium2学习-025-WebUI自动化实战实例-023-页面快照截图应用之一 -- 常规截图(全页面)
- VB.net工程的引用修改问题
- mysql 的分库分表操作
- HDU 1232 畅通工程 并查集
- 用MVC结构写web小程序时出现“ Cannot forward after response has been committed”的错误
- 背单词App开发日记5(上)
- Java程序设计之正则表达式
- PROBLEM_B: URAL 2025 B - Line Fighting
- memory currentMemory memballooon
- JAVA流程控制语句
- iOS Quartz2D - 矩阵操作
- 九度oj 1109
- C语言:顺序结构(数组)栈
- C++ sort()
- 第四课,T语言运算符(版本5.0)
- 二分图详解及总结
- $_FILE['myfile']
- Legal or Not(拓扑排序判环)