125.Valid Palindrome - 验证回文串

Palindrome : palin-,重,再,-drome,跑,词源同dromedary,hippodrome.

n.1.回文(顺读和倒读都一样的词、短语、诗句等,如:radar, rotator) 2.【生物化学】回文节,回文结构;旋转对称

https://leetcode-cn.com/problems/valid-palindrome/ 

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

题意分析:一个字符串,只考虑字母和数字字符,忽略大小写,验证是否是回文串

ps:本题中空字符串定义为有效的回文串。

思路:

1、首先剔除无关的字符,只保留字母及数字字符,考虑使用Character.isLetterOrDigit

2、对过滤后的字符串,

  2.1.考虑字符串反转,得到新的字符串,与原字符串相比,相等返回true;

  2.2.考虑双指针,左右指针分别指向字符串的两侧,将这两个指针不断地相向移动,每次移动一步,并判断这两个指针指向的字符是否相同。当这两个指针相遇时,就说明该字符串是回文串。

 public boolean isPalindrome(String s) {
        //1、筛选出字母及字符,字母统一大写或小写
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (Character.isLetterOrDigit(ch)) {
                sb.append(Character.toLowerCase(ch));
            }
        }
        //2.1、字符串反转对比
        StringBuffer sb_rev = new StringBuffer(sb).reverse();
        return sb.toString().equals(sb_rev.toString());
    }

 

public boolean isPalindrome(String s) {
        //1、筛选出字母及字符,字母统一大写或小写
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (Character.isLetterOrDigit(ch)) {
                sb.append(Character.toLowerCase(ch));
            }
        }
  
        //2.2、双指针相向移动
        int left = 0, right = sb.length() - 1;
        while(left < right){
            if (Character.toLowerCase(sb.charAt(left)) != Character.toLowerCase(sb.charAt(right))) {
                return false;
            }
            left++;
            right--;
        }

        return true;
    }

 

 

 

 

你可能感兴趣的:(LeetCode,-,algorithm)