欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

确定给定字符串是否为回文字符串。

最编程 2024-06-08 07:32:16
...

朋友出的小题,练手。

/**
 * 
 * @author Jason Li 2014-5
 * 判断一个字符串是否是回文串(字符串从左向右读,与 从右向左读都一样)
 *
 */
public class StringPalindrome {

	public static void main(String[] args) {

		String str = "abcdefedcba";
		System.out.println(isPalindrom(str));
	}

	private static boolean isPalindrom(String str) {
		//转成char数组
		char[] temp = str.toCharArray(); 
		//左右两边扫描,如果不一样,直接返回false
		for (int i = 0, j = temp.length - 1; i < temp.length >> 1; i++, j--) {
			if (temp[i] != temp[j]) return false;
		}
		return true;
	}

}


当然也可以使用现成的东西,不过都这样写面试官估计就生气了:

/**
 * 
 * @author Jason Li 2014-5
 * 判断给定的字符串是否是回文
 */
public class StringPalindromeSimple {
	
	public static void main(String[] args) {
		String str = "abcdedcba";
		StringBuilder sb = new StringBuilder(str); //新建串
		System.out.println(str.equals(sb.reverse().toString()));//反转后直接比较		
	}
}



推荐阅读