码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Permutation

时间:2015-12-21 12:33:40      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

Given a string, determine if a permutation of the string could form a palindrome.

For example,
"code" -> False, "aab" -> True, "carerac" -> True.

 

解法一:

解题思路

The idea is to iterate over string, adding current character to set if set doesn‘t contain that character, or removing current character from set if set contains it. When the iteration is finished, just return set.size()==0 || set.size()==1.

set.size()==0 corresponds to the situation when there are even number of any character in the string, and set.size()==1 corresponsds to the fact that there are even number of any character except one.

 1 public class Solution {
 2     public boolean canPermutePalindrome(String s) {
 3         Set<Character> set=new HashSet<Character>();
 4         for(int i=0; i<s.length(); ++i){
 5             if (!set.contains(s.charAt(i)))
 6                 set.add(s.charAt(i));
 7             else 
 8                 set.remove(s.charAt(i));
 9         }
10         return set.size()==0 || set.size()==1;
11     }
12 }

reference: https://leetcode.com/discuss/53295/java-solution-w-set-one-pass-without-counters

 

Palindrome Permutation

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5062925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!