【Leetcode】242. Valid Anagram
来源:互联网 发布:广州企业名录数据库 编辑:程序博客网 时间:2024/06/06 09:16
方法一:
思路:
Hash表计数判相等。
public class Solution { public boolean isAnagram(String s, String t) { int lenS = s.length(); int lenT = t.length(); if (lenS != lenT) return false; Map<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < lenS; i++) { if (map.containsKey(s.charAt(i))) map.put(s.charAt(i), map.get(s.charAt(i)) + 1); else map.put(s.charAt(i), 1); } for (int i = 0; i < lenT; i++) { if (map.containsKey(t.charAt(i)) && map.get(t.charAt(i)) > 0) map.put(t.charAt(i), map.get(t.charAt(i)) - 1); else return false; } return true; }}
Runtime:50ms
方法二:
思路:
转换为char[],不用Map,效率提升。
public class Solution { public boolean isAnagram(String s, String t) { int lenS = s.length(); int lenT = t.length(); if (lenS != lenT) return false; char[] ch1 = s.toCharArray(); char[] ch2 = t.toCharArray(); int[] temp = new int[128]; for (char ch : ch1) temp[ch]++; for (char ch : ch2) { temp[ch]--; if (temp[ch] < 0) return false; } return true; }}Runtime:3ms
1 0
- [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
- 242.[LeetCode]Valid Anagram
- NumberUtils的用法
- URI和URL的区别
- linux-centos 为什么crond执行完没有了邮件日子通知?
- Linux下Nginx快捷启动关闭设置
- 1
- 【Leetcode】242. Valid Anagram
- 逆向基础13:联合体
- 掉电时钟保存main函数
- 2
- 大数据初接触
- linux串口驱动分析
- 51单片机60秒倒计时
- 魔方公式总结
- 推荐系统开源软件列表汇总和点评(转)