zoukankan      html  css  js  c++  java
  • LeetCode 125. Valid Palindrome

    原题链接在这里:https://leetcode.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

    题解:

    注意在用Character.isLetterOrDigit(s.charAt(i)) 前需检验 i 是否index out of bound 了.

    Note: if first check i < j.

    Time Complexity: O(n), n = s.length().

    Space: O(1).

    AC Java:

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

     跟上Valid Palindrome II.

  • 相关阅读:
    第五章4
    第五章3
    第五章2
    第五章1
    第四章14
    第四章13
    第四章12
    第四章11
    第五章例5-6
    第五章例5-4
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5015593.html
Copyright © 2011-2022 走看看