680. Valid Palindrome II
string,logic
Given a string s
, return true
if the s
can be palindrome after deleting at most one character from it.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= s.length <= 10
5
s
consists of lowercase English letters.
分析
错误思路:贪心思想,左边删掉可以的话就继续,但是事实上可能后续失败
但是其实删掉右边可能就可以了,但因为左边已经走下去了,无法验证了
字符串结构分析
Copy
初始时
l=0
('c'
),r=8
('u'
),发现s[0] != s[8]
('c' != 'u'
)。原代码会尝试跳过左边或右边的字符:
检查
s[l+1] == s[r]
:s[1] = 'u'
vss[8] = 'u'
→ 匹配,于是跳过s[0]
的'c'
,移动指针l=2
,r=7
。接下来比较
s[2]
('p'
)和s[7]
('c'
),发现不匹配,但此时change=1
(已跳过一次),直接返回False
。
问题根源
原代码在第一次跳过 'c'
后,剩余的字符串是 "upuupuc"
,它本身不是回文(因为 'p' != 'c'
),但原代码没有全局验证跳过后的子串是否整体回文,而是仅检查了相邻字符,导致误判。
Last updated
Was this helpful?