-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_680_ValidPalindromeII.cpp
71 lines (58 loc) · 1.4 KB
/
LC_680_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
/*
https://leetcode.com/problems/valid-palindrome-ii/
680. Valid Palindrome II
*/
class Solution {
public:
/*
bool validPalindrome(string s) {
if(s.size()==0) return true;
int i=0;
int j=s.size()-1;
while(i<j)
{
if(s[i] != s[j])
return chkPalindrome(s, i+1, j) || chkPalindrome(s, i, j-1);
i++; j--;
}
return true;
}//end
bool chkPalindrome(string &s, int i, int j)
{
while(i<j)
{
if(s[i]!=s[j])
return false;
i++; j--;
}
return true;
}
*/
bool validPalindrome(string s) {
if(s.size()==0) return true;
int i=0;
int j=s.size()-1;
while(i<j)
{
if(s[i] != s[j]) // if one character is mismatched
{
int i1 = i+1, j1 = j;
int i2 = i, j2 = j-1;
while(i1 < j1 && s[i1] == s[j1])
{
i1++;
j1--;
}
while(i2 < j2 && s[i2] == s[j2])
{
i2++;
j2--;
}
return i1>=j1 || i2>=j2;
}
i++;
j--;
}
return true;
}//end
};