#include <iostream>#include <stdio.h>#include <vector>#include <algorithm>#include <string>using namespace std;/*問題: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.分析:此題實際是判斷一個字符串是否是回文字符串,不考慮大小寫,比較的時候只比較字母和數字,對于其他字符默認忽略。設定從前向后和從后向前兩個指針分別為low ,highA[low]或者A[high]不是數字或字母,則直接過濾,否則統一將字符轉換為小寫,并比較是否相等low >= high的時候結束易錯:如果是空字符串,直接是回文的。容易遺漏輸入:A man, a plan, a canal: Panamarace a car輸出:truefalse關鍵:1 易錯:如果是空字符串,直接是回文的。容易遺漏2 將字符串轉換為小寫,用的是transform函數(beg , end , where , func)transform(s.begin() , s.end() , s.begin() , tolower);*/class Solution {public: bool isPalindrome(string s) { if(s.empty()) { return true; } //將字符串轉換為小寫,用的是transform函數(beg , end , where , func) //transform(s.begin() , s.end() , s.begin() , tolower); int len = s.length(); for(int i = 0 ; i < len ; i++) { if('A' <= s.at(i) && s.at(i) <= 'Z') { s.at(i) = s.at(i) - 'A' + 'a'; } } int low = 0; int high = len - 1; while(low < high) { while(low < high && !( ('0' <= s.at(low) && s.at(low) <= '9') || ('a' <= s.at(low) && s.at(low) <= 'z') ) ) { low++; } if(low >= high) { return true; } while(low < high && !( ('0' <= s.at(high) && s.at(high) <= '9') || ('a' <= s.at(high) && s.at(high) <= 'z') ) ) { high--; } if(low >= high) { return true; } //比較兩個字符是否相同,先轉換為小寫,比較之后,還需要變換下標 if(s.at(low) != s.at(high)) { return false; } low++; high--; } return true; }};void process(){ vector<int> nums; Solution solution; vector<int> result; char str[1024]; //對于有空格的字符串,直接用gets while(gets(str) ) { string value(str); bool isOk = solution.isPalindrome(value); if(isOk) { cout << "true" << endl; } else { cout << "false" << endl; } }}int main(int argc , char* argv[]){ process(); getchar(); return 0;}
新聞熱點
疑難解答