zoukankan      html  css  js  c++  java
  • LeetCode125_给定一个字符串_判断是否是回文字符串(只考虑数字和字母_忽略大小写)


    /**
    * 给定一个字符串,判断是否是回文字符串(只考虑数字和字母,忽略大小写)
    * <p>
    * Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
    * <p>
    * Example 1:
    * <p>
    * Input: s = "A man, a plan, a canal: Panama"
    * Output: true
    * Explanation: "amanaplanacanalpanama" is a palindrome.
    * <p>
    * Example 2:
    * <p>
    * Input: s = "race a car"
    * Output: false
    * Explanation: "raceacar" is not a palindrome.
    * <p>
    * Constraints:
    * <p>
    * 1 <= s.length <= 2 * 10^5
    * s consists only of printable ASCII characters.
    */
    public class _125_ValidPalindrome {

    public static void main(String[] args) {
    String s = "A man, a plan, a canal: Panama";
    System.out.println(isPalindrome(s));
    s = "race a car";
    System.out.println(isPalindrome(s));
    s = "0P";
    System.out.println(isPalindrome(s));
    }

    public static boolean isPalindrome1(String s) {
    char[] chars = s.toLowerCase().toCharArray();
    int l = 0;
    int r = chars.length - 1;
    while (l < r) {
    if (!((chars[l] >= 'a' && chars[l] <= 'z') || (chars[l] >= '0' && chars[l] <= '9'))) {
    l++;
    continue;
    }
    if (!((chars[r] >= 'a' && chars[r] <= 'z') || (chars[r] >= '0' && chars[r] <= '9'))) {
    r--;
    continue;
    }
    if (chars[l] != chars[r]) {
    return false;
    }
    l++;
    r--;
    }
    return true;
    }

    /**
    * LeetCode评论区解法之一
    */
    public static boolean isPalindrome(String s) {
    int l = 0;
    int r = s.length() - 1;
    while (l < r) {
    char chL = s.charAt(l);
    if (!Character.isLetterOrDigit(chL)) {
    l++;
    continue;
    }
    char chR = s.charAt(r);
    if (!Character.isLetterOrDigit(chR)) {
    r--;
    continue;
    }
    if (chL >= 'A' && chL <= 'Z') {
    chL = Character.toLowerCase(chL);
    }
    if (chR >= 'A' && chR <= 'Z') {
    chR = Character.toLowerCase(chR);
    }
    if (chL != chR) {
    return false;
    }
    l++;
    r--;
    }
    return true;
    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    bzoj 1503: [NOI 2004]郁闷的出纳员
    bzoj 1001: [BeiJing2006]狼抓兔子
    bzoj 1005: [HNOI2008]明明的烦恼
    bzoj 1004: [HNOI2008]Cards
    bzoj 1003: [ZJOI2006]物流运输trans
    06day1
    05day2
    04day2
    04day1
    03day2
  • 原文地址:https://www.cnblogs.com/laydown/p/15056789.html
Copyright © 2011-2022 走看看