-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path680.valid-palindrome-ii.py
More file actions
82 lines (76 loc) · 1.89 KB
/
680.valid-palindrome-ii.py
File metadata and controls
82 lines (76 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#
# @lc app=leetcode id=680 lang=python3
#
# [680] Valid Palindrome II
#
# https://leetcode.com/problems/valid-palindrome-ii/description/
#
# algorithms
# Easy (33.89%)
# Total Accepted: 69.4K
# Total Submissions: 203.9K
# Testcase Example: '"aba"'
#
#
# 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.
#
#
# TLE
# class Solution:
# def validPalindrome(self, s: str) -> bool:
# if self.isPalindrome(s):
# return True
# ret = False
# for i in range(len(s)):
# new_s = s[:i] + s[(i + 1):]
# if self.isPalindrome(new_s):
# ret = True
# break
# return ret
# def isPalindrome(self, s):
# return s == s[::-1]
# class Solution:
# def validPalindrome(self, s: str) -> bool:
# if self.isPalindrome(s):
# return True
# low, high = 0, len(s) - 1
# strPart = lambda s, x: s[:x] + s[x + 1:]
# while low < high:
# if s[low] != s[high]:
# return self.isPalindrome(strPart(s, low)) or self.isPalindrome(strPart(s, high))
# low += 1
# high -= 1
# return True
# def isPalindrome(self, s):
# return s == s[::-1]
class Solution:
def validPalindrome(self, s: str) -> bool:
def is_pali_range(i, j):
return all(s[k] == s[j - k + i] for k in range(i, j))
for i in range(len(s) // 2):
if s[i] != s[~i]:
j = len(s) - 1 - i
return is_pali_range(i + 1, j) or is_pali_range(i, j - 1)
return True