日期:2014-05-20  浏览次数:20842 次

【面试】一道Java面试题
偶然在论坛上看到了一道面试题,题目如下:

问题: 如果给定的字符串从左到右和从右到左的序列完全一致,那么这样的字符串被称为 palindrome。例如,下面的字符串都是 palindromes。 "kayak"   "codilitytilidoc"   "neveroddoreven" 如果字符串A和字符串B含有相同的字母,但是顺序可能不一样,那么A被称为是B的anagram。例如,下面的字符串互为anagrams: A="mary" B="army" A="rocketboys" B="octobersky" A="codility" B="codility"

希望各位贴出自己的代码,下面是我写的,大家看看有问题么,希望大家改进。


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);
	}

}