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

Twitter OA prepare: Anagram is A Palindrome

Algorithm:

  1. Count the number of occurrence of each character.

  2. Only one character with odd occurrence is allowed since in a palindrome maximum number of character with odd occurrence can be '1'.

  3. All other character should occur in even number of times.

  4. If (2) and (3) fail, then the given string is not a palindrome.

 1 public int check(String str) {
 2     HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 3     for (int i=0; i<str.length(); i++) {
 4         char c = str.charAt(i);
 5         if (map.containsKey(c)) {
 6             map.put(c, map.get(c)+1);
 7         }
 8         else {
 9             map.put(c, 1);
10         }
11     }
12   
13     int cntOdd = 0;
14     for (int val : map.values()) {
15         if (val % 2 == 1) {
16             cntOdd++;
17         }
18     }
19     return cntOdd>1? 0 : 1;
20 }

 

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