LeetCode Palindrome Permutation

时间:2022-09-05 16:16:17

原题链接在这里: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:

 public class Solution {
public boolean canPermutePalindrome(String s) {
if(s == null || s.length() <= 1){
return true;
}
HashSet<Character> hs = new HashSet<Character>();
for(int i = 0; i<s.length(); i++){
char c = s.charAt(i);
if(!hs.contains(c)){
hs.add(c);
}else{
hs.remove(c);
}
}
return hs.size() == 0 || hs.size() == 1;
}
}

可以用bitMap

Time Complexity: O(n). Space: O(256).

 public class Solution {
public boolean canPermutePalindrome(String s) {
if(s == null || s.length() <= 1){
return true;
}
int [] map = new int[256];
for(int i = 0; i<s.length(); i++){
map[s.charAt(i)]++;
}
int count = 0;
for(int i = 0; i<256; i++){
if(count == 0 && map[i]%2 == 1){ //第一次出现frequency为奇数的char
count++;
}else if(map[i] % 2 == 1){ //第二次出现frequency为奇数的char
return false;
}
}
return true;
}
}

类似Longest Palindrome.

跟上Palindrome Permutation II.