LeetCode Palindrome Permutation
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 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 }
以上是关于LeetCode Palindrome Permutation的主要内容,如果未能解决你的问题,请参考以下文章