[LeetCode]125.Valid Palindrome
【題目】
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.
【代碼】
【方法1】
/********************************* * 日期:2013-12-09 * 作者:SJF0115 * 題目: 125.Valid Palindrome * 來源:https://oj.leetcode.com/problems/valid-palindrome/ * 結果:AC * 來源:LeetCode * 總結: **********************************/ class Solution { public: bool isStr(char &ch){ //數字 if(ch >= '0' && ch <= '9'){ return true; } //小寫字母 else if(ch >= 'a' && ch <= 'z'){ return true; } //大寫字母 else if(ch >= 'A' && ch <= 'Z'){ //轉換為小寫 ch += 32; return true; } return false; } bool isPalindrome(string s){ int i,j; int len = s.length(); if(len == 0){ return true; } string str = ""; //去掉非數字字母字符 for(i = 0; i < len; i++){ if(isStr(s[i])){ str += s[i]; } } len = str.length(); for(i = 0,j = len - 1; i < j; i++,j--){ if(str[i] != str[j]){ return false; } } return true; } };
【方法2】
class Solution { public: bool isStr(char &ch){ //數字 if(ch >= '0' && ch <= '9'){ return true; } //小寫字母 else if(ch >= 'a' && ch <= 'z'){ return true; } //大寫字母 else if(ch >= 'A' && ch <= 'Z'){ //轉換為小寫 ch += 32; return true; } return false; } bool isPalindrome(string s){ int i,j; int len = s.length(); if(len == 0){ return true; } len = s.length(); for(i = 0,j = len - 1; i < j;){ if(!isStr(s[i])){ i++; continue; } if(!isStr(s[j])){ j--; continue; } if(s[i] != s[j]){ return false; } i++; j--; } return true; } };

【測試】
/********************************* * 日期:2013-12-09 * 作者:SJF0115 * 題號: 題目: Valid Palindrome * 來源:https://oj.leetcode.com/problems/valid-palindrome/ * 結果:AC * 來源:LeetCode * 總結: **********************************/ #include <iostream> #include <stdio.h> using namespace std; class Solution { public: bool isStr(char &ch){ //數字 if(ch >= '0' && ch <= '9'){ return true; } //小寫字母 else if(ch >= 'a' && ch <= 'z'){ return true; } //大寫字母 else if(ch >= 'A' && ch <= 'Z'){ //轉換為小寫 ch += 32; return true; } return false; } bool isPalindrome(string s){ int i,j; int len = s.length(); if(len == 0){ return true; } string str = ""; //去掉非數字字母字符 for(i = 0; i < len; i++){ if(isStr(s[i])){ str += s[i]; } } len = str.length(); for(i = 0,j = len - 1; i < j; i++,j--){ if(str[i] != str[j]){ return false; } } return true; } }; int main() { bool result; string str = "A man, a plan, a canal: Panama"; //string str = "race a car"; Solution solution; result = solution.isPalindrome(str); if(result){ printf("This is a Palindrome\n"); } else{ printf("sorry\n"); } return 0; }
最後更新:2017-04-03 12:53:42