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 3253 Fence Repair
    POJ 2431 Expedition
    NYOJ 269 VF
    NYOJ 456 邮票分你一半
    划分数问题 DP
    HDU 1253 胜利大逃亡
    NYOJ 294 Bot Trust
    NYOJ 36 最长公共子序列
    HDU 1555 How many days?
    01背包 (大数据)
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3580450.html
Copyright © 2011-2022 走看看