LeetCode 266. Palindrome Permutation
原题链接在这里:https://leetcode.com/problems/palindrome-permutation/
题目:
Given a string, determine if a permutation of the string could form a palindrome.
For example,"code"
-> False, "aab"
-> True, "carerac"
-> True.
题解:
看能否配对出现.
Time Complexity: O(n). Space: O(n).
AC Java:
1 public class Solution { 2 public boolean canPermutePalindrome(String s) { 3 if(s == null || s.length() <= 1){ 4 return true; 5 } 6 HashSet<Character> hs = new HashSet<Character>(); 7 for(int i = 0; i<s.length(); i++){ 8 char c = s.charAt(i); 9 if(!hs.contains(c)){ 10 hs.add(c); 11 }else{ 12 hs.remove(c); 13 } 14 } 15 return hs.size() == 0 || hs.size() == 1; 16 } 17 }
可以用bitMap
Time Complexity: O(n). Space: O(256).
1 public class Solution { 2 public boolean canPermutePalindrome(String s) { 3 if(s == null || s.length() <= 1){ 4 return true; 5 } 6 int [] map = new int[256]; 7 for(int i = 0; i<s.length(); i++){ 8 map[s.charAt(i)]++; 9 } 10 int count = 0; 11 for(int i = 0; i<256; i++){ 12 if(count == 0 && map[i]%2 == 1){ //第一次出现frequency为奇数的char 13 count++; 14 }else if(map[i] % 2 == 1){ //第二次出现frequency为奇数的char 15 return false; 16 } 17 } 18 return true; 19 } 20 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步