-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid_palindrome_II.cpp
102 lines (75 loc) · 1.85 KB
/
valid_palindrome_II.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
96
97
98
99
100
101
102
#include<iostream>
#include<string.h>
using namespace std;
bool isPalindrome(string s, int low, int high)
{
// int low = 0;
//int high = s.length() - 1;
while (low < high)
{
if (s[low] != s[high])
return false;
low++;
high--;
}
return true;
}
// This method returns -1 if it is not possible to make string
// a palindrome. It returns -2 if string is already a palindrome.
// Otherwise it returns index of character whose removal can
// make the whole string palindrome.
bool validPalindrome(string str)
{
int result;
// Initialize low and right by both the ends of the string
int low = 0, high = str.length() - 1;
if(isPalindrome(str, low, high)) return true;
// loop untill low and high cross each other
while (low < high)
{
// If both characters are equal then move both pointer
// towards end
if (str[low] == str[high])
{
low++;
high--;
}
else
{
/* If removing str[low] makes the whole string palindrome.
We basically check if substring str[low+1..high] is
palindrome or not. */
if (isPalindrome(str, low + 1, high))
{
result = low;
break;
}
/* If removing str[high] makes the whole string palindrome
We basically check if substring str[low+1..high] is
palindrome or not. */
if (isPalindrome(str, low, high - 1))
{
result = high;
break;
}
else{
result = -1;
break;
}
}
}
// We reach here when complete string will be palindrome
// if complete string is palindrome then return mid character
if(result == -1)
{
return 0;
}
return 1;
}
// Driver code to test above methods
int main()
{
string str = "abcddcba";
cout << validPalindrome(str) << endl;
return 0;
}