leetcode 刷题:Valid Palindrome(回文字符串)

来源:互联网 发布:手机五线谱记谱软件 编辑:程序博客网 时间:2024/05/04 12:54

题目:

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.

思路:先将字符串中的字母跟数字按顺序提取出来放到一个新的字符串中,再用while循环比较新的字符串相对应位置的字符是否相等。

若出现不相等的情况则返回false,循环完毕都没有返回FALSE,则是回文字符串。

注意:比较的时候是忽略大小写的。

public class Solution2 {
    public boolean isPalindrome(String s) {
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<s.length();i++){
            if(Character.isDigit(s.charAt(i)) || Character.isLetter(s.charAt(i))){
            System.out.println(s.charAt(i));
                sb.append(s.charAt(i));
            }
        }
        String str = sb.toString();
        System.out.println(str);
        int j = 0;
        int k = str.length()-1;
        boolean isPalindrome = true;
        while(j<=k){
            if(Character.toUpperCase(str.charAt(j)) == Character.toUpperCase(str.charAt(k))){
                j++;
                k--;
            }else{
                return false;
            }
        }
        return isPalindrome;
    }
    
    public static void main(String[] args) {
    Solution2 s2 = new Solution2();
    System.out.println(s2.isPalindrome("`l;`` 1o1 ??;l`"));
}
  }


结果输出true.  

0 0
原创粉丝点击