您的位置:首页 > 其它

LeetCode Palindrome Permutation

2016-03-11 12:20 363 查看
原题链接在这里: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++){
if(!hs.contains(s.charAt(i))){
hs.add(s.charAt(i));
}else{
hs.remove(s.charAt(i));
}
}
return hs.size() == 1 || hs.size() == 0;
}
}


可以用bitMap

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;
}
}


跟上Palindrome Permutation II.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: