首页 > 其他 > 详细

Twitter OA prepare: Anagram is A Palindrome

时间:2015-03-09 12:36:42      阅读:313      评论:0      收藏:0      [点我收藏+]

技术分享

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 }

 

Twitter OA prepare: Anagram is A Palindrome

原文:http://www.cnblogs.com/EdwardLiu/p/4323200.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!