Leetcode ☞ 242. Valid Anagram ☆
来源:互联网 发布:如何练出完美胸肌知乎 编辑:程序博客网 时间:2024/05/17 04:02
网址:https://leetcode.com/problems/valid-anagram/
Total Accepted: 62627 Total Submissions: 153094 Difficulty: Easy
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?
我的AC(笨):
//ASCII码:0--48 A--65 a--97 范围是0~127。bool isAnagram(char* s, char* t) { int Hash1[256], Hash2[256], flag = 0;//数组范围128的话会不够 memset(Hash1,0,257 * sizeof(int)); memset(Hash2,0,257 * sizeof(int)); if (strlen(s) != strlen(t)) return false; while(*s){ Hash1[*s++]++;//*s++:先*s,再s++。 Hash2[*t++]++; } for(int i = 0; i < 257 ; i++){ if(Hash1[i] != Hash2[i]){ flag = 1; break; } } return flag ? false : true;}
讨论区里的很nice的解答,比我的笨方法运算少:
https://leetcode.com/discuss/83342/0ms-fastest-c-solution
bool isAnagram(char* s, char* t) { if(strlen(s) != strlen(t)) { return false; } int mask[256] = {}; char *c = s; while(*c) { mask[*c++]++; } c = t; while(*c) { if(mask[*c] > 0) { mask[*c++]--; } else { return false; } } return true;}
分析:
1.数组的范围问题:http://blog.sina.com.cn/s/blog_a401a1ea0101fh3z.html
2.注意 *s++的运算顺序:先*s,再s++。“++”作用在地址上,而(*s)++里的“++”是作用在数值上。
python,高级语言真是偷奸耍滑的不行:
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ a = list(s) b = list(t) c = a.sort() d = b.sort() for i,j in zip(c,d): if i != j: return False return True
0 0
- Leetcode ☞ 242. Valid Anagram ☆
- [leetcode] 242.Valid Anagram
- leetcode 242. Valid Anagram
- [leetcode] 242. Valid Anagram
- leetCode 242. Valid Anagram
- Leetcode 242. Valid Anagram
- 242. Valid Anagram LeetCode
- 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
- java创建对象的4中方法
- 卫康直销如何安全的参与中国MMM互助金融社区系统?
- python实现高精度减法
- CSS3 入门2
- JQuery Uploadify 基于JSP的无刷新上传实例
- Leetcode ☞ 242. Valid Anagram ☆
- [BZOJ 4196][Noi2015]软件包管理器
- ytu 2242 回文(栈和队列)
- why+how+what
- 修改Ubuntu的默认启动项
- 安装clustalw-2.1
- 第一个简单的程序
- ftrace用法
- Android开发中可能遇到的坑