Twitter OA prepare: Anagram is A Palindrome
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 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步