LeetCode#242 Valid Anagram (week5)
来源:互联网 发布:a算法解决八数码问题 编辑:程序博客网 时间:2024/06/03 20:18
week5
题目
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.
原题地址:https://leetcode.com/problems/valid-anagram/description/
解析
题目大意是给两个字符串,判断它们是否一个字符串能否通过打乱顺序得到另一个字符串,是则返回true,反之返回false。注意到Note中提示可以考虑字符串中的字符仅为小写字母,因此字符串中的每个字符只有26种可能。
大致思路为用一个大小为26的int字符串,分别代表a-z,检索两个字符串的每个字符,对第一个字符串中出现的字符,对相应的数组+1,对于第二个字符串中出现的字符,相应数组-1,如果两个字符串仅仅顺序不同,则最终数组的每个元素均为0。
代码
class Solution {public: bool isAnagram(string s, string t) { /*如果两个字符串长度不同则可以直接认定两个字符串存在除顺序之外的差别*/ if (s.length() != t.length()) { return false; } int *counter = new int[26]; for (int i = 0; i < 26; ++i) { counter[i] = 0; } for (int i = 0; i < s.length(); ++i) { int pos1 = (int)(s[i] - 'a'); counter[pos1]++; int pos2 = (int)(t[i] - 'a'); counter[pos2]--; } for (int i = 0; i < 26; ++i) { if (counter[i] != 0) { return false; } } return true; }};
阅读全文
0 0
- LeetCode#242 Valid Anagram (week5)
- Leetcode #242 Valid Anagram
- leetcode-242-Valid Anagram
- leetcode 242: Valid Anagram
- 【LeetCode】242 Valid Anagram
- [leetcode 242]Valid Anagram
- leetCode #242 Valid Anagram
- Leetcode #242 Valid Anagram
- LeetCode 242 Valid Anagram
- [LeetCode 242] Valid Anagram
- LeetCode(242)Valid Anagram
- leetcode[242] Valid Anagram
- leetcode 242 :Valid Anagram
- LeetCode 242----Valid Anagram
- 【LeetCode】242Valid Anagram
- Leetcode #242 Valid Anagram
- LeetCode 242:Valid Anagram
- LeetCode 242 Valid Anagram
- 【LINUX】定时任务
- vector容器
- POJ
- unity_NGUI系统学习(九)_Slider滑动器的使用
- 学习生信的系列教程
- LeetCode#242 Valid Anagram (week5)
- Jzoj4595 String
- java的异常及其处理
- Vue2.0 探索之路——vuex入门教程和思考
- 带宽时延乘积的含义
- extjs4 form getFieldValues 和 getValues 的区别
- android view触摸事件传递机制测试
- 【数位DP】HDU2089[不要62]题解
- 重装系统后,github的修改