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
原创粉丝点击