-
Notifications
You must be signed in to change notification settings - Fork 10
/
cheapestPalindrome.java
72 lines (59 loc) · 1.4 KB
/
cheapestPalindrome.java
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
//https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-manipulation/practice-problems/algorithm/make-the-cheapest-palindrome-1/
import java.util.*;
class cheapestPalindrome
{
public static void main(String args[] ) throws Exception
{
Scanner in = new Scanner(System.in);
int T = Integer.parseInt(in.nextLine());
for (int i = 0; i < T; i++)
{
String str = in.nextLine();
int aCost = Integer.parseInt(in.nextLine());
int bCost = Integer.parseInt(in.nextLine());
int cost = 0;
char chars1[] = str.toCharArray();
char chars2[] = new StringBuilder(str).reverse().toString().toCharArray();
int flag = 0;
for(int k=0; k<chars1.length; k++)
{
if( (chars1[k] == '/') &&(chars2[k] == '/') )
{
if(aCost<bCost)
{
chars1[k] = 'a';
cost += aCost;
}
else
{
chars1[k] = 'b';
cost += bCost;
}
}
else if(chars1[k] == '/')
{
if(chars2[k] == 'a')
{
chars1[k] = 'a';
cost += aCost;
}
else
{
chars1[k] = 'b';
cost += bCost;
}
}
else if(chars2[k] == '/')
{}
else if(chars1[k] != chars2[k])
{
cost = -1;
break;
}
else
{}
}
System.out.println(cost);
}
}
}