zoukankan      html  css  js  c++  java
  • LeetCode

    Valid Palindrome

    2014.1.13 18:48

    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.

    Solution:

      This problem doesn't involve maths or difficult algorithms, so it's the kind of easy problem to test if you're careful enough to solve it one-pass. Make NO mistake.

      Time complexity is O(n), where n is the length of the string. Space complexity is O(1).

    Accepted code:

     1 // 1RE, 1AC, be more careful, could've 1AC~
     2 class Solution {
     3 public:
     4     bool isPalindrome(string s) {
     5         // IMPORTANT: Please reset any member data you declared, as
     6         // the same Solution instance will be reused for each test case.
     7         int i, j, len;
     8         
     9         len = s.length();
    10         if(len <= 0){
    11             return true;
    12         }
    13         
    14         char a, b;
    15         
    16         i = 0;
    17         j = len - 1;
    18         while(i < j){
    19             if(s[i] >= 'a' && s[i] <= 'z'){
    20                 a = s[i];
    21             }else if(s[i] >= '0' && s[i] <= '9'){
    22                 a = s[i];
    23             }else if(s[i] >= 'A' && s[i] <= 'Z'){
    24                 a = s[i] - 'A' + 'a';
    25             }else{
    26                 ++i;
    27                 continue;
    28             }
    29             if(s[j] >= 'a' && s[j] <= 'z'){
    30                 b = s[j];
    31             }else if(s[j] >= '0' && s[j] <= '9'){
    32                 b = s[j];
    33             }else if(s[j] >= 'A' && s[j] <= 'Z'){
    34                 b = s[j] - 'A' + 'a';
    35             }else{
    36                 // 1RE here, wrong direction of $j
    37                 --j;
    38                 continue;
    39             }
    40             if(a == b){
    41                 ++i;
    42                 --j;
    43             }else{
    44                 break;
    45             }
    46         }
    47         
    48         return i >= j;
    49     }
    50 };
  • 相关阅读:
    深度优先和广度优先
    水管工游戏(深度优先)
    炸弹人
    广度优先(迷宫找人)
    System.Data.Entity.Core.MetadataException: 无法加载指定的无数据资源
    Element Cascader 级联选择器 单选操作优化
    Windows服务 ProjectInstaller 获取 路径
    Quartz.NET ScheduledFireTimeUtc 当超过1分钟时出现的问题。
    记录:一个SQL SERVER奇怪的问题。
    log4.net 配置
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3517916.html
Copyright © 2011-2022 走看看