标签:delete rom ase The output private solution bre case
问题描述:
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:
解题思路:
首先想到的是暴力破解法,对每一个字母以及不删除进行尝试看能否构成一个回文字符串。
显然,超时了_(:з」∠)_
其实我们可以一开始就检查是否是回文字符串,如果遇到s[left] != s[right]的情况,我们可以尝试删除left或者right来进行判断是否是回文字符串
代码:
class Solution { public: bool validPalindrome(string s) { int left = 0; int right = s.size() -1; bool moved = false; while(left < right){ if(left == right) break; if(s[left] != s[right]){ if(isPalindromeWithoutChar(s, left)) return true; if(isPalindromeWithoutChar(s, right)) return true; return false; } left++; right--; } return true; } private: bool isPalindromeWithoutChar(string &s, int idx){ int left = 0; int right = s.size() - 1; while(left < right){ if(left == idx) left++; else if(right == idx) right--; if(s[right] != s[left]) return false; left++; right--; } return true; } };
标签:delete rom ase The output private solution bre case
原文地址:https://www.cnblogs.com/yaoyudadudu/p/9194367.html