• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Palindrome Permutation

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 }

 

posted @ 2015-12-23 11:32  neverlandly  阅读(235)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3