Given a string S consisting of lowercase English characters, determine if you can make it a palindrome by removing at most 1 character.
Examples:
tacocats→true, because removing one character givestacocatabaabbaaba
Idea:
- Use two pointers, one from the left and one from the right.
- If the characters match, continue inward.
- If they do not match, try skipping either the left character or the right character.
- If either remaining substring is a palindrome, the answer is
true.
这题考察双指针判断回文的经典变体:字符串只允许删除至多一个字符,所以先从左右两端向中间扫描,一旦遇到不相等的位置,就分别尝试跳过左边字符或右边字符,再检查剩余区间是否仍是回文。这样可以在 O(n) 时间内完成判断,核心是把“最多删一个字符”的约束转化成两次局部回文验证。
正文完