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;
        }
    };
    

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

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

  • 相关阅读:
    poj 2773 利用欧拉函数求互质数
    poj3358:欧拉定理
    poj:2992 因子数量
    poj3696:同余方程,欧拉定理
    USACO5.4-Character Recognition
    hdu5017:补题系列之西安网络赛1011
    hdu5014:number sequence对称思想
    欧拉函数,欧拉定理例题整理
    POJ 3463 Sightseeing (次短路)
    POJ
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3580450.html
Copyright © 2011-2022 走看看