A Title:
Given a string, it determines whether or not write a function of one arrangement of a palindromic sequence.
Palindrome string is correct reverse two directions are the same word or phrase. Means arranged to rearrange the letters.
Palindrome string is not necessarily a dictionary word among.
示例1:
输入:"tactcoa"
输出:true(排列有"tacocat"、"atcocta",等等)
Second Solution:
1. The first solution to a problem:
(1) problem-solving ideas:
- Every character number is an even number, or the number of times one and only one occurrence of the characters is odd, a palindromic arrangement; otherwise not
- HashSet using repetitive nature of the element is not determined
- Converting the character string into a character array c1 s
- Create a new HashSet set
- C1 cycle using the set of elements added to
- If not added previously added successfully, then, that for the first time added
- If add failed, then it proves that the element has been added before, so I can remove the element
- After the cycle, if the number of elements set to 0 or 1, demonstrate that the character string matches the
- Otherwise does not comply
(2) Code:
/**
* 思路:
* 每个字符出现的次数为偶数, 或者有且只有一个字符出现的次数为奇数时, 是回文的排列; 否则不是
* 利用HashSet中的元素不重复性质来判定
* 将字符串s转换成字符数组c1
* 新建一个HashSet set
* 利用循环将c1中的元素添加进set中
* 若添加成功,则说明之前没有添加,即第一次添加
* 若添加失败,则证明该元素在之前就已经添加过,所以将该元素移除即可
* 循环结束后,若set的元素个数为0或者1,则证明该字符串符合条件
* 否则不符合
*/
public static boolean canPermutePalindrome(String s) {
Set<Character> set = new HashSet<Character>();
char[] c1 = s.toCharArray();
for(char c:c1){
if(!set.add(c)){
set.remove(c);
}
}
return set.size()<=1;
}