1. 程式人生 > >【LeetCode & 劍指offer刷題】字串題12:Valid Palindrome(迴文詞系列)

【LeetCode & 劍指offer刷題】字串題12:Valid Palindrome(迴文詞系列)

  【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note:  For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input:
"A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false   //問題:迴文(判斷一個字串是否是迴文的,這裡僅考慮字母數字字元,且忽略大小寫 //方法:雙指標法,分別從開頭和結尾掃描 using namespace std ; #include <locale>
//本地化庫的一部分,包含字元分類、轉換等函式 class Solution { public :     bool isPalindrome ( string s )     {         for ( int i = 0 , j =
s . size ()- 1 ; i < j ; i ++, j --) //雙指標,分別從開頭和結尾開始掃描         {             while ( isalnum ( s [ i ]) == false && i < j ) i ++; //如果不是字母數字字元(alphanumeric),增加左指標             while ( isalnum ( s [ j ]) == false && i < j ) j --; //如果不是字母數字字元(alphanumeric),增加右指標                         if ( toupper ( s [ i ]) != toupper ( s [ j ])) return false ; //如果不匹配就退出         }         return true ;     } };     680 .   Valid Palindrome II Given a non-empty string   s , you may delete   at most   one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. Note:
  1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
  //問題:迴文2(判斷一個字串是否是迴文,可以最多刪除一個字元,而且字串中只有小寫英文字母,最大長度為50000) //方法:雙指標法,借用迴文1的解法 #include <iostream> class Solution { public :     bool validPalindrome ( string s )     {         for ( int i = 0 , j = s . size ()- 1 ; i < j ; i ++, j --) //雙指標,分別從開頭和結尾開始掃描         {             if ( s [ i ] != s [ j ]) //掃描到不匹配字元時,刪除其中一個,然後繼續掃描             {                 int i1 = i , j1 = j - 1 ; //“刪除”右邊元素                 int i2 = i + 1 , j2 = j ; //“刪除”左邊元素                                 while ( i1 < j1 && s [ i1 ] == s [ j1 ]) //繼續掃描剩餘元素                 {                     i1 ++;                     j1 --;                 }                 while ( i2 < j2 && s [ i2 ] == s [ j2 ])                 {                     i2 ++;                     j2 --;                 }                 return i1 >= j1 || i2 >= j2 ; //i1>=j1代表已經掃描完畢,字母均匹配             }         }                 return true ;     } };