266 Palindrome Permutation
来源:互联网 发布:python能用来做什么 编辑:程序博客网 时间:2024/06/10 00:00
理解了题意,化简的意思就是,出现次数为奇数的字母 的数量不能超过1个。。
我之前的代码就是按这个思路写的,要过一次string,还要过一次map,效率只有10-20%;
public class Solution { public boolean canPermutePalindrome(String s) { Map<Character, Integer> map = new HashMap<>(); for(char ch: s.toCharArray()){ if(!map.containsKey(ch)) map.put(ch, 0); map.put(ch, map.get(ch)+1); } int oddCount=0; for(char ch: map.keySet()){ if(map.get(ch)%2==1) oddCount++; if(oddCount==2) return false; } return true; }}
只过一次的方法,one-pass就能完成,就是通过set的add 和 remove,来统计出现奇数次的字母。。set内没有就add,有就remove,set的最终大小就是奇数的个数
直达最终结果,中间的数量不重要所以忽略不计,效率达到50%,代码如下:
public class Solution { public boolean canPermutePalindrome(String s) { Set<Character> set = new HashSet<>(); for(int i=0; i<s.length(); i++){ if(!set.contains(s.charAt(i))) set.add(s.charAt(i)); else set.remove(s.charAt(i)); } return set.size()==1 || set.size()==0; }}
0 0
- [LeetCode 266]Palindrome Permutation
- 266 Palindrome Permutation
- [Leetcode 266] Palindrome Permutation
- 266 Palindrome Permutation
- 266 Palindrome Permutation
- Leetcode NO.266 Palindrome Permutation
- Palindrome Permutation
- Palindrome Permutation
- Palindrome Permutation
- Leetcode: Palindrome Permutation
- *LeetCode-Palindrome Permutation
- 1.4 Palindrome Permutation
- [LeetCode266]Palindrome Permutation
- [LeetCode267]Palindrome Permutation II
- Leetcode - 266. Palindrome Permutation
- Leetcode266 Palindrome Permutation
- LeetCode 266. Palindrome Permutation
- Palindrome Permutation II
- 242 Valid Anagram
- Unity3D说明文档翻译-Unity Services
- 介绍一个好用的工具类库commons-beanutils
- 高精度加法(c++)
- Linux系统常见目录说明
- 266 Palindrome Permutation
- 堆
- OD脱壳-再次载入-软件无法找到入口
- [BZOJ3939][Usaco2015 Feb]Cow Hopscotch(cdq分治)
- java日志组件介绍(common-logging,log4j,slf4j,logback )
- HDU 3068 最长回文 (回文自动机)
- 数据结构—Problem B: 删除区间内的元素(线性表)
- Python3 基础语法,从入门到精通一
- Python3 基础语法 从入门到精通二