[LeetCode] 680. Valid Palindrome II 验证回文字符串 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:
- The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
125. Valid Palindrome 的拓展,给定一个非空字符串,最多可删除1个字符,判断是否可以变成回文。
解法:还是从首尾两边开始比较,如果匹配就移动指针继续比较。当遇到不匹配的时候,删除左边的字符或者右边的字符,只要有一种能匹配就继续。
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution( object ): def validPalindrome( self , s): """ :type s: str :rtype: bool """ def validPalindrome(s, left, right): while left < right: if s[left] ! = s[right]: return False left, right = left + 1 , right - 1 return True left, right = 0 , len (s) - 1 while left < right: if s[left] ! = s[right]: return validPalindrome(s, left, right - 1 ) or validPalindrome(s, left + 1 , right) left, right = left + 1 , right - 1 return True |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Solution { public : bool validPalindrome(string s) { int left = 0, right = s.length() - 1; while (left < right) { if (s[left] != s[right]) { return validPalindrome(s, left, right - 1) || validPalindrome(s, left + 1, right); } ++left, --right; } return true ; } private : bool validPalindrome( const string& s, int left, int right) { while (left < right) { if (s[left] != s[right]) { return false ; } ++left, --right; } return true ; } }; |
类似题目:
[LeetCode] 125. Valid Palindrome 验证回文字符串
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步