首页 > 其他 > 详细

Palindrome Permutation

时间:2015-12-21 12:30:39      阅读:101      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!