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

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    启动WCF多个服务方法
    获取本机内存使用信息、DataTable占用内存空间
    分享到微博代码
    EXCEL拼接SQL
    动态调用webservice及WCF服务
    整洁架构
    端口与适配器架构
    清晰架构
    EBI架构 VS. MVC
    查看Oracle加锁情况及解锁方法
  • 原文地址:https://www.cnblogs.com/laydown/p/15056789.html
Copyright © 2011-2022 走看看