原题链接在这里:https://leetcode.com/problems/palindrome-permutation/
题目:
Given a string, determine if a permutation of the string could form a palindrome.
For example,"code"
-> False, "aab"
-> True, "carerac"
-> True.
题解:
看能否配对出现.
Time Complexity: O(n). Space: O(n).
AC Java:
1 public class Solution { 2 public boolean canPermutePalindrome(String s) { 3 if(s == null || s.length() <= 1){ 4 return true; 5 } 6 HashSet<Character> hs = new HashSet<Character>(); 7 for(int i = 0; i<s.length(); i++){ 8 char c = s.charAt(i); 9 if(!hs.contains(c)){ 10 hs.add(c); 11 }else{ 12 hs.remove(c); 13 } 14 } 15 return hs.size() == 0 || hs.size() == 1; 16 } 17 }
可以用bitMap
Time Complexity: O(n). Space: O(256).
1 public class Solution { 2 public boolean canPermutePalindrome(String s) { 3 if(s == null || s.length() <= 1){ 4 return true; 5 } 6 int [] map = new int[256]; 7 for(int i = 0; i<s.length(); i++){ 8 map[s.charAt(i)]++; 9 } 10 int count = 0; 11 for(int i = 0; i<256; i++){ 12 if(count == 0 && map[i]%2 == 1){ //第一次出现frequency为奇数的char 13 count++; 14 }else if(map[i] % 2 == 1){ //第二次出现frequency为奇数的char 15 return false; 16 } 17 } 18 return true; 19 } 20 }