-
Notifications
You must be signed in to change notification settings - Fork 3
/
1328.cpp
35 lines (33 loc) · 870 Bytes
/
1328.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
class Solution {
public:
string breakPalindrome(string palindrome) {
int n = palindrome.size();
if (n == 1) return "";
// count a
int aCnt = 0;
int notAIdx = INT_MAX;
for (int i = 0; i < n; ++i) {
if (palindrome[i] == 'a') aCnt++;
else notAIdx = min(notAIdx, i);
}
if (aCnt == n) {
palindrome[n - 1] = 'b';
return palindrome;
}
// find first not a
if (n & 1) {
if (notAIdx == n / 2) {
palindrome[n - 1] = 'b';
return palindrome;
}
else {
palindrome[notAIdx] = 'a';
return palindrome;
}
}
else {
palindrome[notAIdx] = 'a';
return palindrome;
}
}
};