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;
    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    6.数字三角形
    5.分组背包问题
    1.商品模块表结构分析
    AUTH_USER_MODEL refers to model 'user.User' that has not been installed
    发布品论接口
    查询指定课程评论接口
    1.评论模块表结构
    上传视频课程到七牛云后存储到django后端接口
    5.上传视频到七牛云django端实现
    4.七牛云上传前台页面
  • 原文地址:https://www.cnblogs.com/laydown/p/15056789.html
Copyright © 2011-2022 走看看