码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Palindrome Permutation

时间:2016-03-11 14:07:50      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5265142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!