【LeetCode & 劍指offer刷題】字串題12:Valid Palindrome(迴文詞系列)
阿新 • • 發佈:2019-01-05
【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)
"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:
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:- The string will only contain lowercase characters a-z. The maximum length of the string is 50000.