首页 > 代码库 > Twitter OA prepare: Anagram is A Palindrome
Twitter OA prepare: Anagram is A Palindrome
A string is a palindrome if it has exactly the same sequence of characters when traversed left-to-right as right-to-left. For example, the following strings are palindromes:"kayak""codilitytilidoc""neveroddoreven"A string A is an anagram of a string B if it consists of exactly the same characters, but possibly in another order. For example, the following strings are each other‘s anagrams:A="mary" B="army" A="rocketboys" B="octobersky" A="codility" B="codility"Write a functionint isAnagramOfPalindrome(String S);which returns 1 if the string s is a anagram of some palindrome, or returns 0 otherwise.For example your function should return 1 for the argument "dooernedeevrvn", because it is an anagram of a palindrome "neveroddoreven". For argument "aabcba", your function should return 0.
Algorithm:
Count the number of occurrence of each character.
Only one character with odd occurrence is allowed since in a palindrome maximum number of character with odd occurrence can be ‘1‘.
All other character should occur in even number of times.
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。