日期:2014-05-20 浏览次数:21087 次
package com.qustion;
import java.util.Arrays;
public class TestPalindrome {
/**
* @param args
* @author lohasle
* @time 2012/03/19
*/
// 判断 s的某种anagram是palindrome
public int isAnagramOfPalindrome(String str) {
char[] ch = splitString(str);
if (str != null) {
int[] sata = totalSee(ch);
if (sata[1] > 1) {
return 0;
} else {
if (sata[0] % 2 == 0||sata[1]==1) {
return 1;
} else {
return 0;
}
}
} else {
return 0;
}
}
// 拆分成字符数组 返回排好序的字符数组 为之后的遍历查找 赋值做准备
public char[] splitString(String str) {
int len = str.length();
char[] ch = new char[len];
for (int i = 0; i < len; i++) {
ch[i] = str.charAt(i);
}
for (int i = 0; i < ch.length - 1; i++) {
int minPos = i;// 记录最小的位置
for (int j = i + 1; j < ch.length; j++) {
if (ch[j] < ch[minPos]) {
minPos = j;
char temp = ch[minPos];
ch[minPos] = ch[i];
ch[i] = temp;
}
}
}
return ch;
}
// 统计相同的字母将它设值为一 统计相同字母出现的
public int[] totalSee(char[] ch) {
int len = ch.length;
int resultCountSame = 0;// 计算相同字母出现的总得次数
int countNoSame = 0;// 独立字母的总个数
int countSame = 1;//每一次查找 获得的相同字母总次数之和 不包括开头的哪一位
int[] a = new int[2];// 统计相同字母的总个数 和 独立字母的总个数
for (int i = 0; i < len; i+=countSame) {
for (int j = i + 1; j < len; j++) {
if (ch[j] !='1') {
if (ch[i] == ch[j]) {
countSame++;
ch[j] = '1';// 计算完之后 为了统计别 的字母 将值1作为标志
} else {
continue;
}
}
}ch[i] ='1';//这里是开始计算的首字母
}
for(int i = 0;i<len;i++){
if(ch[i]=='1'){
resultCountSame++;
}else{
countNoSame++;
}
}
a[0] = resultCountSame;
a[1] = countNoSame;
return a;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* String str = "aasasasaaa"; TestPalindrome te = new TestPalindrome();
* System.out.println(Arrays.toString(te.splitString(str)));
* System.out.println(Arrays.toString(str.split("a")));
*/
TestPalindrome te = new TestPalindrome();
String testStr = "kayak";
int result = te.isAnagramOfPalindrome(testStr);
System.out.println(result);
}
}