diff --git "a/problems/0072.\347\274\226\350\276\221\350\267\235\347\246\273.md" "b/problems/0072.\347\274\226\350\276\221\350\267\235\347\246\273.md" index cc4ab00cdc..703e891311 100644 --- "a/problems/0072.\347\274\226\350\276\221\350\267\235\347\246\273.md" +++ "b/problems/0072.\347\274\226\350\276\221\350\267\235\347\246\273.md" @@ -40,6 +40,8 @@ exection -> execution (插入 'u') * 0 <= word1.length, word2.length <= 500 * word1 和 word2 由小写英文字母组成 +# 算法公开课 +**《代码随想录》算法视频公开课:[动态规划终极绝杀! LeetCode:72.编辑距离](https://www.bilibili.com/video/BV1we4y157wB/),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 ## 思路 diff --git "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" index 4474f1c613..6dd3cd4975 100644 --- "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" +++ "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" @@ -467,9 +467,57 @@ class Solution: return " ".join(words) ``` - Go: +版本一: + +```go +func reverseWords(s string) string { + b := []byte(s) + + // 移除前面、中间、后面存在的多余空格 + slow := 0 + for i := 0; i < len(b); i++ { + if b[i] != ' ' { + if slow != 0 { + b[slow] = ' ' + slow++ + } + for i < len(b) && b[i] != ' ' { // 复制逻辑 + b[slow] = b[i] + slow++ + i++ + } + } + } + b = b[0:slow] + + // 翻转整个字符串 + reverse(b) + // 翻转每个单词 + last := 0 + for i := 0; i <= len(b); i++ { + if i == len(b) || b[i] == ' ' { + reverse(b[last:i]) + last = i + 1 + } + } + return string(b) +} + +func reverse(b []byte) { + left := 0 + right := len(b) - 1 + for left < right { + b[left], b[right] = b[right], b[left] + left++ + right-- + } +} +``` + +版本二: + ```go import ( "fmt"