• [Leetcode] valid palindrome 验证回文


    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.

    题意:给定字符串,判断是否为回文。值得注意的是,只考虑字符和数字且不考虑字符大写小,其他情况忽略。

    思路:判断是否为回文的情况,一般都是用两个指针,从字符串的两端开始向中间移动,若对应位置的字符不等则返回false。这里的区别在于,有空格和符号,而这些都是题中要求忽略的,所以,每当遇到空格和符号时,直接跳过就行,反应在代码上就是一个加加,一个减减;还有一点就是,这里是不考虑大小写的,所以需要写一个函数,遇到大写的时候转化成小写去比较(也可以小转大),其他不变。代码如下:

     1 class Solution {
     2 public:
     3     bool isPalindrome(string s) 
     4     {
     5         int len=s.size();
     6         if(len==0)  return true;
     7 
     8         int l=0,r=len-1;
     9         while(l<r)
    10         {
    11             if( !isAlpnum(s[l]))
    12                 l++;
    13             else if( !isAlpnum(s[r]))
    14                 r--;
    15             else if(toLower(s[l]) !=toLower(s[r]))
    16                 return false;
    17             else
    18             {
    19                 l++;
    20                 r--;
    21             }     
    22         }
    23         return true;
    24     }
    25 
    26     bool isAlpnum(const char c)
    27     {
    28         if('A'<=c&&c<='Z')
    29             return true;
    30         else if('a'<=c&&c<='z')
    31             return true;
    32         else if('0'<=c&&c<='9')
    33             return true;
    34         return false;
    35     }
    36 
    37     char toLower(const char c)
    38     {
    39         if('A'<=c&&c<='Z')
    40             return c+32;
    41         return c;
    42     }
    43 };

    其中判断是否为字母和数字可以用函数isalnum,这样就可以少写一个函数,其余不变。参考了booirror的博客。

  • 相关阅读:
    微信JS SDK Demo
    两种方法实现在HTML页面加载完毕后运行某个js
    JS 页面加载触发事件 document.ready和onload的区别
    Thinkphp3.2添加QQ互联和新浪微博一键登录功能
    bootstrap-select实现下拉框多选效果
    Sass (Syntactically Awesome StyleSheets)
    常见MFC UI界面库[转]
    VTK序列图像的读取[转][改]
    c语言-格式控制字符 %XXd 用法
    3DSlicer源代码编译过程vs2008+windows xp [转]
  • 原文地址:https://www.cnblogs.com/love-yh/p/7161025.html
Copyright © 2020-2023  润新知