zoukankan      html  css  js  c++  java
  • LeetCode 125. Valid Palindorme (验证回文字符串)

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

    For example,
    "A man, a plan, a canal: Panama" is a palindrome.
    "race a car" is not a palindrome.

    Note:
    Have you consider that the string might be empty? This is a good question to ask during an interview.

    For the purpose of this problem, we define empty string as valid palindrome.


    题目标签:String, Two Pointers

      题目给了我们一个string s, 让我们判断它是不是 palindorme。

      对于s, 我们只需要比较 字母 和 数字。

           设置一个 left = 0, right = s.length() -1,依次比较,其中遇到任何其他 char 就跳过,具体看code。

      一开始不知道有 Character.isLetterOrDigit() ,还分别用了 letter 和 digit - -

    Java Solution:

    Runtime beats 80.01% 

    完成日期:03/07/2017

    关键词:two pointers

    关键点:skip all non-alphanumeric chars

     1 class Solution 
     2 {
     3     public boolean isPalindrome(String s) 
     4     {
     5         // use two pointers
     6         int left = 0;
     7         int right = s.length() - 1;
     8         
     9         char [] char_arr = s.toCharArray();
    10         
    11         while(left < right)
    12         {
    13             while(left < right && !Character.isLetterOrDigit(char_arr[left])) // if char is not letter or digit
    14                 left++;
    15             
    16             while(left < right && !Character.isLetterOrDigit(char_arr[right])) // if char is not letter or digit
    17                 right--;
    18 
    19             if(Character.toUpperCase(char_arr[left]) != Character.toUpperCase(char_arr[right]))
    20                 return false;
    21             
    22             left++;
    23             right--;
    24         }
    25         
    26         return true;
    27     }
    28     
    29 
    30 }

    参考资料:n/a

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    hash
    C#执行Sql事务处理
    数据库的锁表
    页面的刷新 和图片的替换
    单点登录 Webservice
    js 动态调用js文件
    .net生成EXCEL
    JS : 连续滚动
    引用指定类型的对象
    对象序列化为字符串
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/8845773.html
Copyright © 2011-2022 走看看