Skip to content

Commit 0f9fef3

Browse files
authored
feat: add solutions to lc problems: No.2976,2977 (#2161)
1 parent 86a1bda commit 0f9fef3

File tree

9 files changed

+1338
-6
lines changed

9 files changed

+1338
-6
lines changed

solution/2900-2999/2976.Minimum Cost to Convert String I/README.md

+12
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,18 @@
6969

7070
<!-- 这里可写通用的实现逻辑 -->
7171

72+
**方法一:Floyd 算法**
73+
74+
根据题目描述,我们可以将每个字母看作一个节点,每对字母的转换成本看作一条有向边。那么我们先初始化一个 $26 \times 26$ 的二维数组 $g$,其中 $g[i][j]$ 表示字母 $i$ 转换成字母 $j$ 的最小成本。初始时 $g[i][j] = \infty$,如果 $i = j$,那么 $g[i][j] = 0$。
75+
76+
然后我们遍历数组 $original$、$changed$ 和 $cost$,对于每个下标 $i$,我们将 $original[i]$ 转换成 $changed[i]$ 的成本 $cost[i]$ 更新到 $g[original[i]][changed[i]]$ 中,取最小值。
77+
78+
接下来,我们使用 Floyd 算法计算出 $g$ 中任意两个节点之间的最小成本。最后,我们遍历字符串 $source$ 和 $target$,如果 $source[i] \neq target[i]$,并且 $g[source[i]][target[i]] \geq \infty$,那么说明无法完成转换,返回 $-1$。否则,我们将 $g[source[i]][target[i]]$ 累加到答案中。
79+
80+
遍历结束后,返回答案即可。
81+
82+
时间复杂度 $O(m + n + |\Sigma|^3)$,空间复杂度 $O(|\Sigma|^2)$。其中 $m$ 和 $n$ 分别是数组 $original$ 和 $source$ 的长度;而 $|\Sigma|$ 是字母表的大小,即 $|\Sigma| = 26$。
83+
7284
<!-- tabs:start -->
7385

7486
### **Python3**

solution/2900-2999/2976.Minimum Cost to Convert String I/README_EN.md

+12
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,18 @@ It can be shown that this is the minimum possible cost.
5757

5858
## Solutions
5959

60+
**Solution 1: Floyd Algorithm**
61+
62+
According to the problem description, we can consider each letter as a node, and the conversion cost between each pair of letters as a directed edge. We first initialize a $26 \times 26$ two-dimensional array $g$, where $g[i][j]$ represents the minimum cost of converting letter $i$ to letter $j$. Initially, $g[i][j] = \infty$, and if $i = j$, then $g[i][j] = 0$.
63+
64+
Next, we traverse the arrays $original$, $changed$, and $cost$. For each index $i$, we update the cost $cost[i]$ of converting $original[i]$ to $changed[i]$ to $g[original[i]][changed[i]]$, taking the minimum value.
65+
66+
Then, we use the Floyd algorithm to calculate the minimum cost between any two nodes in $g$. Finally, we traverse the strings $source$ and $target$. If $source[i] \neq target[i]$ and $g[source[i]][target[i]] \geq \infty$, it means that the conversion cannot be completed, so we return $-1$. Otherwise, we add $g[source[i]][target[i]]$ to the answer.
67+
68+
After the traversal ends, we return the answer.
69+
70+
The time complexity is $O(m + n + |\Sigma|^3)$, and the space complexity is $O(|\Sigma|^2)$. Where $m$ and $n$ are the lengths of the arrays $original$ and $source$ respectively; and $|\Sigma|$ is the size of the alphabet, that is, $|\Sigma| = 26$.
71+
6072
<!-- tabs:start -->
6173

6274
### **Python3**

0 commit comments

Comments
 (0)