forked from Nanduag0/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 3
/
BreakAPalindrome.txt
64 lines (63 loc) · 1.4 KB
/
BreakAPalindrome.txt
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
class Solution {
public:
string breakPalindrome(string palindrome)
{
if(palindrome.length()==1)
{
return "";
}
int i=0;
int y=0;
int lastpos=0;
for(int i=0;i<palindrome.length();i++)
{
if(palindrome[i]=='a')
{
lastpos=i;
}
}
i=0;
while(i<palindrome.length())
{
char ch='a';
if(palindrome[i]!='a')
{
char tmp=palindrome[i];
while(ch<=tmp)
{
palindrome[i]=ch;
if(!(isPalindrome(palindrome)))
return palindrome;
ch+=1;
}
}
else if(palindrome[i]=='a' && i==lastpos)
{
ch='b';
while(ch<='z')
{
palindrome[i]=ch;
if(!(isPalindrome(palindrome)))
return palindrome;
ch+=1;
}
}
i++;
}
return palindrome;
}
bool isPalindrome(string p)
{
int m=0,n=p.length()-1;
while(m<=n)
{
if(p[m]!=p[n])
{
return false;
}
m++;
n--;
}
return true;
}
};