zoukankan      html  css  js  c++  java
  • LeetCode | Valid Palindrome

    Valid Palindrome

     Total Accepted: 55178 Total Submissions: 251068My Submissions

    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.

    Show Tags
    Have you met this question in a real interview? 
    Yes
     
    No

    Discuss


    思路:首先把给定字符串里的是数字或者字母的存起来到temp字符串,然后对temp进行判断,思路还是很清晰的。如果一个字符是,那么我就应该将它添加到这个temp中,但是实现遇到了一点麻烦,主要是字符没办法直接添加到temp中。解决方案是:

    char tmp[1];

    tmp[0]=s[i];  //是数字或者字母

    string result(tmp,1);

    temp+=result;

    实现代码如下:

    class Solution {
    public:
        bool isPalindrome(string s) {
           string temp;
           for(int i=0;i<s.length();i++)
           {
               if(isalnum(s[i])){
                if(s[i]>='A'&&s[i]<='Z')
                    s[i]=s[i]+32;
                char tmp[1];
                tmp[0] = s[i] ;
                string result(tmp,1);
                temp+=result;
               }
           }
          // cout<<temp<<endl;
           for(int i=0,j=temp.length()-1;i<j;i++,j--)
           {
               if(temp[i]!=temp[j])
                return false;
           }
           return true;
        }
    };

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    特殊集合
    推箱子
    集合
    数组

    循环语句 练习题
    穷举与迭代
    循环语句
    练习题
    switch case
  • 原文地址:https://www.cnblogs.com/Tobyuyu/p/4965324.html
Copyright © 2011-2022 走看看