CC--Q1.4

1.4 Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rea rrangement of letters. The palindrome does not need to be limited to just dictionary words.
EXAMPLE
Input: Tact Coa
Output: True (permutations: "taco cat". "atco cta". etc.)

Just check that no more than one character appears an odd number of times. Because if there is one, then it must be in the middle of the palindrome. So we can't have two of them.

For even Palindrome, all char number must be even
For odd palindrome, all char number must be even except one odd.

public boolean canPermutePalindrome(String s) {
        Set<Character> set=new HashSet<Character>();
        for(int i=0; i<s.length(); i++){
            if (!set.contains(s.charAt(i)))
                set.add(s.charAt(i));
            else 
                set.remove(s.charAt(i));
        }
        return set.size()==0 || set.size()==1;
    }

Or reduce the space usage by using a bit vector

public boolean canPermutePalindrome(String s) {
    BitSet bs = new BitSet();
    for (byte b : s.getBytes())
        bs.flip(b);
    return bs.cardinality() < 2;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,776評論 0 33
  • 最近我剛剛看完了一本書,是美國作家埃克哈特·托利的靈性書籍《當下的力量》。這本書由《遇見未知的自己》的作者,同是靈...
    毛球女神進化館閱讀 1,718評論 3 6
  • 很喜歡在夜深人靜的時候,獨自放上一曲緩緩的歌——陶醉、享受!此刻,正循環播放著史逸欣的《綠島小夜曲》。 想寫下點什...
    不聽話閱讀 561評論 0 1
  • 每天又忙又累!但是沒有充實感,甚至迷茫于為何奔波!有時突然夢醒卻有不知身在何處的感覺!
    花樣兒閱讀 134評論 0 0