LeetCode Palindrome Permutation

原题链接在这里: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             if(!hs.contains(s.charAt(i))){
 9                 hs.add(s.charAt(i));
10             }else{
11                 hs.remove(s.charAt(i));
12             }
13         }
14         return hs.size() == 1 || hs.size() == 0;
15     }
16 }

 可以用bitMap

 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 }

 跟上Palindrome Permutation II.

你可能感兴趣的:(LeetCode Palindrome Permutation)