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

Leetcode: Palindrome Permutation

时间:2015-12-23 13:00:34      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

Given a string, determine if a permutation of the string could form a palindrome.

For example,
"code" -> False, "aab" -> True, "carerac" -> True.

Hint:

  1. Consider the palindromes of odd vs even length. What difference do you notice?
  2. Count the frequency of each character.
  3. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
 1 public class Solution {
 2     public boolean canPermutePalindrome(String s) {
 3         if (s==null || s.length()==0) return true;
 4         int[] count = new int[256];
 5         for (int i=0; i<s.length(); i++) {
 6             char c = s.charAt(i);
 7             count[(int)(c - ‘\0‘)]++;
 8         }
 9         int countOdd = 0;
10         for (int i=0; i<256; i++) {
11             if (count[i]%2 == 1) countOdd++;
12         }
13         if (s.length()%2==0 && countOdd==0) return true;
14         if (s.length()%2==1 && countOdd==1) return true;
15         return false;
16     }
17 }

 

Leetcode: Palindrome Permutation

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5069359.html

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