-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPalindrome with minimum sum.cpp
84 lines (61 loc) · 1.52 KB
/
Palindrome with minimum sum.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
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
int minimumSum(string s) {
// code here
int n = s.size();
int i = 0, j = n-1;
auto posConvert = [&](){
while(i <= j)
{
if(s[i] != '?' and s[j] != '?' and s[i] != s[j])
return false;
if(s[i] == '?' and s[j] != '?')
s[i] = s[j];
else if(s[i] != '?' and s[j] == '?')
s[j] = s[i];
++i, --j;
}
return true;
};
if(!posConvert())
{
return -1;
}
i = 0;
while(i < n and s[i] == '?')
++i;
if(i == n)
return 0;
char prev = s[i];
int ans = 0;
for(int j = i+1; j < n; ++j)
{
if(s[j] == '?')
s[j] == prev;
ans += abs(s[j] - prev);
prev = s[j];
}
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
Solution ob;
int ans = ob.minimumSum(s);
cout << ans;
cout << "\n";
}
return 0;
}
// } Driver Code Ends