MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / Solution

Class Solution

minimumCostToConvertString1.java:1–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Solution {
2 public long minimumCost(String source, String target, char[] original, char[] changed, int[] cost) {
3 int[][] dis = new int[26][26];
4 for (int i = 0; i < 26; i++) {
5 Arrays.fill(dis[i], Integer.MAX_VALUE);
6 dis[i][i] = 0;
7 }
8 for (int i = 0; i < cost.length; i++) {
9 int start = original[i] - 'a';
10 int end = changed[i] - 'a';
11 dis[start][end] = Math.min(dis[start][end], cost[i]);
12 }
13 for (int k = 0; k < 26; k++) {
14 for (int i = 0; i < 26; i++)
15 if (dis[i][k] < Integer.MAX_VALUE) {
16 for (int j = 0; j < 26; j++) {
17 if (dis[k][j] < Integer.MAX_VALUE) {
18 dis[i][j] = Math.min(dis[i][j], dis[i][k] + dis[k][j]);
19 }
20 }
21 }
22 }
23 long ans = 0L;
24 for (int i = 0; i < source.length(); i++) {
25 int c1 = source.charAt(i) - 'a';
26 int c2 = target.charAt(i) - 'a';
27 if (dis[c1][c2] == Integer.MAX_VALUE) {
28 return -1L;
29 } else {
30 ans += (long)dis[c1][c2];
31 }
32 }
33 return ans;
34 }
35}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected