这道easy题我不知道为什么做了一个小时,思路是很快的,想了5分钟就有了正确思路,就是之后一直在改bug,各种边界问题,变量值改变之类的。先说下思路吧:一个string要是能改成回文,那这个string最多只能有一个character出现的次数为奇数。想想真的很简单怪不得easy题呢,结果我做起来真的是乱七八杂,各种数据结构乱用,虽然我是做出来了,但是真的很乱。但毕竟是自己孩子,我还是得展示一下自己代码:
class Solution {
public boolean canPermutePalindrome(String s) {
//去除s中重复元素
StringBuffer sb = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (s.indexOf(c) ==s.lastIndexOf(c)) {//此字符第一次位置和最后位置一致 即肯定没有重复的直接添加
sb.append(c);
} else {//同理 次字符出现过多次
int fristposition=s.indexOf(c);//次字符第一次出现的位置
if(fristposition==i){//第一次出现的位置和当前位置一致 即第一次出现添加
sb.append(c);
}
}
}
String newString = sb.toString(); //得到新的没有重复的string
//比较newString与s中的元素
int hh = 0;
for(int i =0; i< newString.length(); i++){
int count = 0;
for(int j =0; j< s.length(); j++){
if(newString.charAt(i)==s.charAt(j)){
count++;
}
}
hh += count % 2;
}
return hh <= 1;
}
}
下面给出官方思路一以及其代码,思路真的是和我差不多,只不过他很巧妙用到了ascii码,将128个ascii分别和string中的character进行比较,统计出现次数为奇数的character的个数。而我是剔除了string中的重复元素,得到一个新string,然后用这个新string和原来的string进行比较,也是统计出出现次数为奇数的character的个数。下面给出官方解答代码:
public class Solution {
public boolean canPermutePalindrome(String s) {
int count = 0;
for (char i = 0; i < 128 && count <= 1; i++) {
int ct = 0;
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == i)
ct++;
}
count += ct % 2;
}
return count <= 1;
}
}
最后我想分享一个very elegant solution这个方法是利用set不能有重复元素的性质。思路和我的也是一样的,统计出现次数为奇数的character的个数。只是这边利用到set的性质,真的很巧妙。下面直接给出代码吧:
public class Solution {
public boolean canPermutePalindrome(String s) {
Set < Character > set = new HashSet < > ();
for (int i = 0; i < s.length(); i++) {
if (!set.add(s.charAt(i)))
set.remove(s.charAt(i));
}
return set.size() <= 1;
}
}
总结:
- string去重可以使用stringbuilder,利用其indexof 和lastindexof方法,把不重复的character,append进stringbuilder里,再用tostring将这个stringbuilder转化为string。
- 要多去了解各种容易类的性质