![JAR search and dependency download from the Maven repository](/logo.png)
g3301_3400.s3361_shift_distance_between_two_strings.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
The newest version!
package g3301_3400.s3361_shift_distance_between_two_strings;
// #Medium #Array #String #Prefix_Sum #2024_12_03_Time_9_ms_(100.00%)_Space_45.8_MB_(36.02%)
public class Solution {
public long shiftDistance(String s, String t, int[] nextCost, int[] previousCost) {
long[][] costs = new long[26][26];
long cost;
for (int i = 0; i < 26; i++) {
cost = nextCost[i];
int j = i == 25 ? 0 : i + 1;
while (j != i) {
costs[i][j] = cost;
cost += nextCost[j];
if (j == 25) {
j = -1;
}
j++;
}
}
for (int i = 0; i < 26; i++) {
cost = previousCost[i];
int j = i == 0 ? 25 : i - 1;
while (j != i) {
costs[i][j] = Math.min(costs[i][j], cost);
cost += previousCost[j];
if (j == 0) {
j = 26;
}
j--;
}
}
int n = s.length();
long ans = 0;
for (int i = 0; i < n; i++) {
ans += costs[s.charAt(i) - 'a'][t.charAt(i) - 'a'];
}
return ans;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy