zoukankan      html  css  js  c++  java
  • [LeetCode] 125. 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

    有效的回文。题意很简单,验证给的input是否是一个有效的回文。思路也很简单,two pointer逼近。注意

    • 只比较input里面的字母和数字
    • 需要ignore大小写

    时间O(n)

    空间O(1)

    JavaScript实现

     1 /**
     2  * @param {string} s
     3  * @return {boolean}
     4  */
     5 var isPalindrome = function (s) {
     6     if (s === null || s.length === 0) return true;
     7     const alphanum = s.toLowerCase().replace(/[W]/g, "");
     8     let left = 0;
     9     let right = alphanum.length - 1;
    10     while (left < right) {
    11         if (alphanum[left] !== alphanum[right]) {
    12             return false;
    13         }
    14         left++;
    15         right--;
    16     }
    17     return true;
    18 };

    Java实现

     1 class Solution {
     2     public boolean isPalindrome(String s) {
     3         // corner case
     4         if (s == null || s.length() == 0) {
     5             return true;
     6         }
     7 
     8         // normal case
     9         int left = 0;
    10         int right = s.length() - 1;
    11         while (left < right) {
    12             while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
    13                 left++;
    14             }
    15             while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
    16                 right--;
    17             }
    18             if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
    19                 return false;
    20             }
    21             left++;
    22             right--;
    23         }
    24         return true;
    25     }
    26 }

    相关题目

    125. Valid Palindrome

    234. Palindrome Linked List

    680. Valid Palindrome II

    LeetCode 题目总结

  • 相关阅读:
    汉语-词语:注重
    汉语-词语:解释
    汉语-词语:接受
    汉语-词语:专注
    汉语-词语:构想
    生物-植物-果树:枣树
    汉语-词语:维度
    汉语-词语:真传
    XML基础知识学习
    Java Swing界面编程(25)---事件处理:鼠标事件及监听处理
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12194820.html
Copyright © 2011-2022 走看看