Valid Palindrome

来源:互联网 发布:ce6.6源码 编辑:程序博客网 时间:2024/04/29 15:43

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.

思路: Using a string builder to storage the string without blank.
Check the sb.charAt(i) == sb.charAt(len - 1 - i);

易错点: 别忘记还有数字

public class Solution {    public boolean isPalindrome(String s) {        if(s.length() < 1){            return true;        }        s = s.toLowerCase();        s.trim();        StringBuilder sb = new StringBuilder();        for(int i = 0; i < s.length(); i++){            char c = s.charAt(i);            if((c >= 'a' && c <= 'z') || (c >='0' && c <= '9')){                sb.append(c);            }        }        for(int i = 0; i < sb.length()/2; i++){            if(sb.charAt(i) != sb.charAt(sb.length() - 1 - i)){                return false;            }        }        return true;    }}


0 0
原创粉丝点击