zoukankan      html  css  js  c++  java
  • Valid Palindromed

    iven 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.

    拿这个练习了下stack。注意top和pop。pop是不返回元素的。

    class Solution {
    public:
        bool isPalindrome(string s) {
            int l = s.length();
            stack<char> st;
            for(int i = 0 ; i < l ; i++)
            {
                if(s[i] >= 'a' && s[i] <= 'z'|| s[i] >='0'&&s[i]<='9')st.push(s[i]);
                else if(s[i] >= 'A' && s[i] <= 'Z') st.push(s[i]-'A'+'a');
                
            }
            
            for(int i = 0 ; i < l ; i++)
            {
                if(s[i] >= 'a' && s[i] <= 'z' || s[i] >='0'&&s[i]<='9')
                {
                    char temp = st.top();
                    st.pop();
                    if(temp != s[i]) return 0;
                }
                else if(s[i] >= 'A' && s[i] <= 'Z')
                {
                    char temp = st.top() -'a'+'A';
                    st.pop();
                    if(temp != s[i]) return 0;
                }
            }
            return 1;
        }
    };
    

      这个题有更优的解法,也不用栈。

         左右两个指针,分别指到第一个合法字符之后开始判断,之后一个向左一个向右,如此反复指到两个指针相遇。

  • 相关阅读:
    Cmake Make makefile GNU autotools
    第三方库的安装:Pangolin
    ./configure, make, sudo make install 的含义
    [Eigen]C++开源线代库
    术语解释
    KDevelop使用笔记【中文教程】
    Python-Day1
    找不到或无法加载主类
    仅仅测试Word2016发布博客
    First Day!
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3580450.html
Copyright © 2011-2022 走看看