-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathValidPalindromeII.cpp
95 lines (65 loc) · 2.07 KB
/
ValidPalindromeII.cpp
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
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Source: https://leetcode.com/problems/valid-palindrome-ii/
1st Approach (Two pointer approach)
Algorithm:
- Take 2 pointers; leftIndex and rightIndex
- Iterate through the string by incrementing the leftIndex and decrementing the rightIndex.
if the two characters on leftIndex and rightIndex are not equal, then delete the character(done using isCharacterDeleted = true).
- Now, iterate through rest of the remaining characters
if two characters are found which are not equal again, then return false
-return true after whole iteration of the string.
Time: O(n), where n is the length of the given string(s)
Space: O(1), constant space
*/
class Solution {
public:
bool validPalindrome(string s) {
return isPalindrome(s, 0, s.size() - 1, false);
}
private:
bool isPalindrome(string s, int leftIndex, int rightIndex, bool isCharDeleted) {
while(leftIndex < rightIndex) {
if(s[leftIndex] != s[rightIndex]) {
if(isCharDeleted) {
return false;
}
return isPalindrome(s, leftIndex + 1, rightIndex, true) || isPalindrome(s, leftIndex, rightIndex - 1, true);
}
++leftIndex;
--rightIndex;
}
return true;
}
};
--------------------------------------------------------------------------------------------------------------------------
/*
2nd Approach(Same idea, but expanded form for better understanding)
Time: O(n), where n is the length of the given string(s)
Space: O(1), constant space
*/
class Solution {
public:
bool validPalindrome(string s) {
int leftIndex = 0;
int rightIndex = s.length() - 1;
while(leftIndex < rightIndex) {
if(s[leftIndex] != s[rightIndex]) {
return isPalindrome(s, leftIndex + 1, rightIndex) || isPalindrome(s, leftIndex, rightIndex - 1);
}
++leftIndex;
--rightIndex;
}
return true;
}
private:
bool isPalindrome(string s, int leftIndex, int rightIndex) {
while(leftIndex < rightIndex) {
if(s[leftIndex] != s[rightIndex]) {
return false;
}
++leftIndex;
--rightIndex;
}
return true;
}
};