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; } };
这个题有更优的解法,也不用栈。
左右两个指针,分别指到第一个合法字符之后开始判断,之后一个向左一个向右,如此反复指到两个指针相遇。