首页 > 其他分享 >LeetCode 2976 Minimum Cost to Convert String I

LeetCode 2976 Minimum Cost to Convert String I

时间:2024-07-27 12:29:03浏览次数:10  
标签:index Convert cost String character source Minimum dist target

Minimum Cost to Convert String I

Problem Description

You are given two 0-indexed strings, source and target, both of length n and consisting of lowercase English letters. You are also provided with two 0-indexed character arrays, original and changed, and an integer array cost, where cost[i] represents the cost of changing the character original[i] to the character changed[i].

The goal is to convert the source string into the target string using the fewest operations possible. Each operation involves changing a character x in source to a character y if a conversion path exists from x to y at a specified cost. If it is impossible to convert source to target, the function should return -1.

Constraints

  • 1 <= source.length == target.length <= 10^5
  • source and target consist of lowercase English letters.
  • 1 <= cost.length == original.length == changed.length <= 2000
  • original[i], changed[i] are lowercase English letters.
  • 1 <= cost[i] <= 10^6
  • original[i] != changed[i]

Example

Example 1

  • Input:
    source = "abcd"
    target = "acbe"
    original = ["a", "b", "c", "c", "e", "d"]
    changed = ["b", "c", "b", "e", "b", "e"]
    cost = [2, 5, 5, 1, 2, 20]
    
  • Output: 28
  • Explanation:
    • Change ‘b’ to ‘c’ at a cost of 5.
    • Change ‘c’ to ‘e’ at a cost of 1.
    • Change ‘e’ to ‘b’ at a cost of 2.
    • Change ‘d’ to ‘e’ at a cost of 20.
    • Total cost = 5 + 1 + 2 + 20 = 28.

Example 2

  • Input:
    source = "aaaa"
    target = "bbbb"
    original = ["a", "c"]
    changed = ["c", "b"]
    cost = [1, 2]
    
  • Output: 12
  • Explanation:
    • Change ‘a’ to ‘c’ at a cost of 1, then ‘c’ to ‘b’ at a cost of 2.
    • Total cost for all occurrences of ‘a’ to ‘b’ = (1 + 2) * 4 = 12.

Example 3

  • Input:
    source = "abcd"
    target = "abce"
    original = ["a"]
    changed = ["e"]
    cost = [10000]
    
  • Output: -1
  • Explanation:
    • It is impossible to convert ‘d’ to ‘e’ with the given operations.

Solution

The solution involves representing each character transformation as a graph edge with associated costs, and using the Floyd-Warshall algorithm to find the shortest path (minimum cost) to convert each character in source to the corresponding character in target.

Python Implementation

class Solution(object):
    def minimumCost(self, source, target, original, changed, cost):
        """
        :type source: str
        :type target: str
        :type original: List[str]
        :type changed: List[str]
        :type cost: List[int]
        :rtype: int
        """
        # Function to convert character to index
        def char_to_index(c):
            return ord(c) - ord('a')
        
        # Initialize the distance matrix with infinity
        inf = float('inf')
        dist = [[inf] * 26 for _ in range(26)]
        
        # Set the distance from each character to itself to zero
        for i in range(26):
            dist[i][i] = 0
        
        # Fill the distance matrix with given conversion costs
        for o, c, z in zip(original, changed, cost):
            o_index = char_to_index(o)
            c_index = char_to_index(c)
            dist[o_index][c_index] = min(dist[o_index][c_index], z)
        
        # Apply Floyd-Warshall algorithm to find shortest paths between all pairs of nodes
        for k in range(26):
            for i in range(26):
                for j in range(26):
                    if dist[i][j] > dist[i][k] + dist[k][j]:
                        dist[i][j] = dist[i][k] + dist[k][j]
        
        # Calculate the total minimum cost to convert source to target
        total_cost = 0
        for s_char, t_char in zip(source, target):
            if s_char == t_char:
                continue
            s_index = char_to_index(s_char)
            t_index = char_to_index(t_char)
            
            # If there's no path from source character to target character, return -1
            if dist[s_index][t_index] == inf:
                return -1
            
            total_cost += dist[s_index][t_index]
        
        return total_cost

Explanation

  1. Character Index Mapping: Each character is mapped to an index using ord(c) - ord('a') to facilitate matrix operations.

  2. Distance Matrix Initialization: A 2D matrix dist is initialized with inf values, except for the diagonal which is set to 0 (cost of converting a character to itself).

  3. Populate Distance Matrix: Using the original, changed, and cost arrays, populate the dist matrix with the minimum costs for direct conversions.

  4. Floyd-Warshall Algorithm: This algorithm is applied to compute the shortest paths between all pairs of characters, taking into account possible intermediary conversions.

  5. Calculate Total Cost: Iterate over source and target, summing the minimum conversion costs. If a character in source cannot be converted to the corresponding character in target, return -1.

  6. Return Result: The total minimum cost is returned, or -1 if the conversion is impossible.

标签:index,Convert,cost,String,character,source,Minimum,dist,target
From: https://blog.csdn.net/weixin_39280437/article/details/140733569

相关文章

  • 「杂题乱刷2」CF1889A Qingshan Loves Strings 2
    vp到的。题目链接CF1889AQingshanLovesStrings2解题思路我们考虑从头到尾依次判断情况。维护两个指针\(l,r\)来依次比较,直到有\(a_l=a_r\)。这种情况根据题目所述是不合法的,因此我们需要依次分讨一下两种情况:\(a_l=a_r=1\),这时我们只需要在\(s_l\)前加上......
  • 04_String类
    一、String字符串是常量,创建之后不可被改变字符串字面值存储在字符串池中,可以共享Strings="Hello";产生一个对象,字符串池中存储Strings=newString("Hello");产生两个对象,堆、池各存储一个。二、常用方法publicintlength();返回字符串长度。publiccharcharAt(inti......
  • 282:vue+openlayers 利用 LineString 显示线段
    作者:还是大剑师兰特,曾为美国某知名大学计算机专业研究生,现为国内GIS领域高级前端工程师,CSDN知名博主,深耕openlayers、leaflet、mapbox、cesium,canvas,echarts等技术开发,欢迎加微信(gis-dajianshi),一起交流。查看本专栏目录-本文是第282个示例文章目录一......
  • MapperStruct 嵌套模型中 List<> 转 List<String>
    废话不多说,上代码 宗旨:将List<A>映射为List<String>一,实体类Source//Source中有一个List<A>publicclassSource{privateStringid;privateStringfrom;privateList<A>to;}//A对象中有个BpublicclassA{privateBb;}//B有个addre......
  • C++ primer plus 第16章string 类和标准模板库, 函数符概念
    C++primerplus第16章string类和标准模板库,函数符概念C++primerplus第16章string类和标准模板库,函数符概念文章目录C++primerplus第16章string类和标准模板库,函数符概念16.5.1函数符概念程序清单16.15functor.cpp16.5.1函数符概念正如STL定......
  • C++ primer plus 第16章string 类和标准模板库, 函数对象
    C++primerplus第16章string类和标准模板库,函数对象C++primerplus第16章string类和标准模板库,函数对象文章目录C++primerplus第16章string类和标准模板库,函数对象16.5函数对象16.5函数对象很多STL算法都使用函数对象–也叫函数符(fiunctor)。......
  • 当你第一次用C++string的assign会遇到这种情况
    当你第一次用string的assign时,会发现有一点小区别,见以下代码:stringstr1;str1.assign("helloC++");cout<<str1<<endl;stringstr2;str2.assign(str1,5);cout<<str1<<endl;stringstr3;str3.assign("helloC++",5);cout<<......
  • 字符串的相关案例和string库函数的使用
    字符串的存储特性:在存储过程中字符串都会在末尾自动添加一个结尾标志符\0                 来表示字符串结束字符串的定义方式有两种:方式一:利用字符数组+双引号的方式定义字符串例如:charstr[4]=“abc”;注意:这里的数组长度要么......
  • 【C#】-byte[]数组和string的互相转化 (四种方法)
    第一种stringstr=System.Text.Encoding.UTF8.GetString(bytes);byte[]decBytes=System.Text.Encoding.UTF8.GetBytes(str);同样的,System.Text.Encoding.Default,System.Text.Encoding.ASCII也是可以的。还可以使用System.Text.Encoding.UTF8.GetString(bytes).TrimEnd('\0......
  • Java基础——String/StringBuilder/StringBuffer区别
    四个方面:不可变性、线程安全、性能、使用场景String:不可变,线程安全,适用于多线程编程。注意:由于String内部字符数组由final修饰,对其进行改变时会创建新的String对象,旧的会被JVM回收,容易触发gc(垃圾回收),这种行为可能会导致频繁的内存分配和垃圾回收,从而引起系统的内存抖动(memor......