242. Valid Anagram
2016-05-14 14:35
190 查看
242. Valid Anagram
Description:Given two strings s and t, write a function to determine if t is an anagram of s.
note:
You may assume the string contains only lowercase alphabets.
Example:
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Link:
https://leetcode.com/problems/valid-anagram/
Analysis:
这道题至少有两种思路:
A. 分别统计字符串s和t中每个字母出现的频率,若相同,则认为两个字符串是由字母顺序颠倒构成的。
B. 在s和t长度相同的情况下,分别找出在字符串s中和t对应的每一个字母,如果每个字母都完全对应,则认为他们是由字母顺序颠倒构成的。
对应这两种思路共有两种方法,见源码。
Source Code(C++):
#include <iostream> #include <string> #include <vector> using namespace std; /********************************分别统计s和t中字母出现的频率到数组中,比较各个字母出现的频率从而得出结果***********************************************/ /* class Solution { public: bool isAnagram(string s, string t) { vector<int> s_alphabet(26, 0), t_alphabet(26, 0); for (int i=0; i<s.length(); i++) { s_alphabet.at(s.at(i)-97)++; } for (int i=0; i<t.length(); i++) { t_alphabet.at(t.at(i)-97)++; } for (int i=0; i<s_alphabet.size(); i++){ if (s_alphabet.at(i) != t_alphabet.at(i)) { return false; } } return true; } }; */ /********************************直接将s中的每一个字母与t比对***********************************************/ class Solution { public: bool isAnagram(string s, string t) { if (s.length() !=t.length()) { return false; } else { for (int i=0; i<s.length(); i++) { int ind = t.find(s.at(i)); if (ind == string::npos) { return false; } else { t.erase(ind, 1); } } return true; } } }; int main() { Solution sol; cout << sol.isAnagram("anagram", "nagaram"); cout << sol.isAnagram("rat", "car"); return 0; }
相关文章推荐
- Java泛型基础
- java运行原理
- 在OpenCV环境下写的两个图像平移C和C++源代码!
- HBase1.0以上版本的API改变
- 判断一个数是不是3的幂——Power of three?
- android之SurfaceView
- windbg vmware win7联机调试环境搭建
- Struts2国际化实例
- HZAU 1001 Handing Out Candies
- Splunk on CentOS 6 相关系统参数调整
- UNITY_INITIALIZE_OUTPUT
- CoreOS的适应场景介绍
- 混用ngui和ugui渲染顺序问题
- 重写virtual时不写关键字会发生什么
- Combination Sum系列问题
- JSP取得绝对路径
- MongoDB 安装
- 学生信息管理系统--常见问题
- 汉宁窗的性质
- 使用JavaMail发送邮件