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

    思路:有效回文。需要一个指向头部的变量和指向尾部的变量,从字符串的两边来遍历,遇到除字母和数字以外的字符则跳过,如果遍历完整个字符串后前后字母都能匹配上,则是回稳返回true.注意:空串也是回文。

            需要注意的几点:1、对大小写不敏感,需要把所有字母小写都转换成大写,或者大写都转换成小写,用toupper()函数。

                                   2、遇到非字母、数字要跳过,用到isalnum()函数

     1 #include <iostream>
     2 #include "ctype.h"
     3 using namespace std;
     4 
     5 bool isPalindrome(string s)
     6 {
     7     int first,last;
     8     first = 0;
     9     last = s.size() - 1;
    10     while (first <= last)
    11     {
    12         while (!(isalnum(s[first])) && first < last)
    13         {
    14             first++;
    15         }
    16         while (!(isalnum(s[last])) && first < last)
    17         {
    18             last--;
    19         }
    20         if (toupper(s[first]) != toupper(s[last]))
    21         {
    22             return false;
    23         }
    24         first++;
    25         last--;
    26     }
    27     return true;
    28 }
    29 
    30 void main()
    31 {
    32     string s = "A man, a plan, a canal: Panama";
    33     bool m = isPalindrome(s);
    34     cout << m << endl;
    35     system("pause");
    36 }
  • 相关阅读:
    java 整型相除得到浮点型
    Interleaving String
    Insert Interval
    Mashup
    R-TREE
    默认以管理员身份运行VS2013/15/17
    C:malloc/calloc/realloc/alloca内存分配函数
    VS2015快捷键
    C++:UNREFERENCED_PARAMETER用法
    VC++常用数据类型及其操作详解
  • 原文地址:https://www.cnblogs.com/tracyhan/p/5614691.html
Copyright © 2011-2022 走看看