Skip to content

Commit 10f75a7

Browse files
authored
Create 680._Valid_Palindrome_II.md
1 parent d45a86f commit 10f75a7

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# 680. Valid Palindrome II
2+
3+
**<font color=red>难度: Easy</font>**
4+
5+
## 刷题内容
6+
7+
> 原题连接
8+
9+
* https://leetcode.com/problems/valid-palindrome-ii/description/
10+
11+
> 内容描述
12+
13+
```
14+
15+
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
16+
17+
Example 1:
18+
Input: "aba"
19+
Output: True
20+
Example 2:
21+
Input: "abca"
22+
Output: True
23+
Explanation: You could delete the character 'c'.
24+
Note:
25+
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
26+
```
27+
28+
## 解题方案
29+
30+
> 思路 1
31+
32+
想直接来个 for loop,看看对应除去该index元素之后的字符串是否为 palindrome 即可
33+
34+
但是直接 Time Limit Exceeded
35+
36+
```python
37+
class Solution(object):
38+
def validPalindrome(self, s):
39+
"""
40+
:type s: str
41+
:rtype: bool
42+
"""
43+
for i in range(len(s)):
44+
if s[:i] + s[i+1:] == s[i+1:][::-1] + s[:i][::-1]:
45+
return True
46+
return False
47+
```
48+
49+
50+
> 思路 2
51+
52+
我们先定义一个reverse变量作为字符串s的翻转版本,例如
53+
54+
```
55+
s = 'abbbbbca'
56+
reverse = 'acbbbbba'
57+
```
58+
59+
然后我们从第一个字符开始比较,直到两边的字符不相等的时候,比如上面的例子我们就是index为1的时候不相等,所以i = 1,此时我们就会面临两个选择:
60+
61+
1. 我们可以舍弃s中index为i的这个元素看看是否可以使其成为palindrome,即让s变成'abbbbca',然后我们可以通过s[i+1:n-i] == reverse[i:n-i-1]来判断
62+
2. 我们可以舍弃reverse中index为i的这个元素(即s中index为n-1-i的这个元素),即让s变成'abbbbba',我们可以通过s[i:n-1-i] == reverse[i+1:n-i]来判断
63+
64+
```python
65+
class Solution(object):
66+
def validPalindrome(self, s):
67+
"""
68+
:type s: str
69+
:rtype: bool
70+
"""
71+
n = len(s)
72+
if n < 3:
73+
return True
74+
75+
reverse = s[::-1]
76+
i = 0
77+
while i < len(s) and s[i] == reverse[i]:
78+
i += 1
79+
return s[i:n-1-i] == reverse[i+1:n-i] or s[i+1:n-i] == reverse[i:n-i-1]
80+
```
81+
82+
83+
84+
> 思路 3
85+
86+
或者我们不搞reverse,直接在s上面原地判断即可
87+
88+
89+
```python
90+
class Solution(object):
91+
def validPalindrome(self, s):
92+
"""
93+
:type s: str
94+
:rtype: bool
95+
"""
96+
n = len(s)
97+
if n < 3:
98+
return True
99+
100+
l, r = 0, n - 1
101+
while l < r and s[l] == s[r]:
102+
l += 1
103+
r -= 1
104+
if l >= r:
105+
return True
106+
else:
107+
return s[l+1:r+1] == s[l+1:r+1][::-1] or s[l:r] == s[l:r][::-1]
108+
```
109+
110+
111+

0 commit comments

Comments
 (0)