首页 > 代码库 > 【LeetCode】- Valid Palindrome(正确的回文)

【LeetCode】- Valid Palindrome(正确的回文)

问题: ]

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
直译:给你一个字符串, 判定它是否是回文(只统计字母、数字,其他字符请忽略)。


For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.


[ 解法1]

先把有效的字母、数字准备好,然后遍历目标字符串,有效的字符放入buffer。

再比较buffer中的字符串和反转后的字符串,如果相同那就是回文,否则不是回文。

点评:这个解法可以被系统accept,但调用了太多api,性能一般。

public class Solution {

	public boolean isPalindrome(String s) {
		StringBuilder buffer = new StringBuilder();
		String tempStr = "abcdefghijklmnopqrstuvwxyz0123456789"; 
		char[] cArr = s.toCharArray();
		for (int i = 0; i < cArr.length; i++) { 
			if (tempStr.contains(String.valueOf(cArr[i]).toLowerCase())) {
				buffer.append(String.valueOf(cArr[i]).toLowerCase());
			}
		}
		String currentStr = buffer.toString();
		String reverseStr = buffer.reverse().toString();
		if (currentStr.equals(reverseStr)) {
			return true;
		}
		return false;
	}
	
}



【LeetCode】- Valid Palindrome(正确的回文)