LeetCode题解:Valid Anagram
来源:互联网 发布:mac windows 共享文件 编辑:程序博客网 时间:2024/06/04 19:02
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的组成字符颠倒顺序构成的。
所以解决问题的思路很简单:
用HashMap创建s中出现的所有字母及其出现次数的映射表,依次比较t中字符及次数就可以得到结果
用一个长度为26的数组存储字母’a’-‘z’对应的出现次数,数组对应的值减去用t中字母的出现次数,只要数组中所有元素的值不为0,就代表匹配失效
其实两种思路本质是一样的:创建映射表,只不过空间开销和时间开销不一样。
代码:
1、
public boolean isAnagram(String s, String t) { if(s == null && t == null) return true; if(s == null || t == null) return false; if(s.length() != s.length()) return false; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for(int i = 0; i < s.length(); i++) { if(map.containsKey(s.charAt(i))) { int value = map.get(s.charAt(i)); map.put(s.charAt(i), ++value); } else { map.put(s.charAt(i), 1); } } for(int j = 0; j < t.length(); j++) { if(map.containsKey(t.charAt(j))) { int value = map.get(t.charAt(j)); if(--value == 0) { map.remove(t.charAt(j)); } else { map.put(t.charAt(j), value); } } else return false; } if(map.isEmpty()) return true; else return false;}
2、
public boolean isAnagram(String s, String t) { int[] count = new int[26]; for(int i = 0;i < s.length();++i){ ++count[s.charAt(i) - 'a']; } for(int i = 0;i < t.length();++i){ --count[t.charAt(i) - 'a']; } for(int i = 0;i < count.length;++i){ if(count[i] != 0){ return false; } } return true; }
0 0
- LeetCode题解:Valid Anagram
- [LeetCode] Valid Anagram 题解
- LeetCode 题解(183): Valid Anagram
- Leetcode题解 242. Valid Anagram
- leetcode题解-242.Valid Anagram
- LeetCode 242 Valid Anagram题解
- LeetCode 242. Valid Anagram 题解(C++)
- Leetcode #242 Valid Anagram
- leetcode-242-Valid Anagram
- Leetcode: Valid Anagram
- 【leetCode】Valid Anagram
- [leetcode] 242.Valid Anagram
- leetcode 242: Valid Anagram
- 【leetcode】Valid Anagram
- [leetcode] Valid Anagram
- LeetCode Valid Anagram
- 【LeetCode】242 Valid Anagram
- [LeetCode] Valid Anagram
- isis dce接收到报文的流程
- C C++中ThreadLocal的实现方式
- 如何在线程中获取spring 管理的bean
- 如何创建圆形头像和圆角图片
- boost------ref的使用(Boost程序库完全开发指南)读书笔记
- LeetCode题解:Valid Anagram
- PhpStrom花括号的设置
- power of two
- uvali5697(DP)
- java 反射机制
- 博客搬家至以下地址
- HDU 5375 DP
- BOM基础
- Redis底层数据结构总结