結果

問題 No.225 文字列変更(medium)
ユーザー shixamo1shixamo1
提出日時 2020-02-17 09:57:50
言語 Go
(1.22.1)
結果
AC  
実行時間 14 ms / 5,000 ms
コード長 1,630 bytes
コンパイル時間 15,594 ms
コンパイル使用メモリ 231,828 KB
実行使用メモリ 9,600 KB
最終ジャッジ日時 2024-04-16 03:45:40
合計ジャッジ時間 13,310 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 10 ms
9,600 KB
testcase_01 AC 12 ms
9,600 KB
testcase_02 AC 7 ms
9,472 KB
testcase_03 AC 8 ms
9,472 KB
testcase_04 AC 7 ms
9,472 KB
testcase_05 AC 7 ms
9,472 KB
testcase_06 AC 7 ms
9,472 KB
testcase_07 AC 7 ms
9,600 KB
testcase_08 AC 7 ms
9,472 KB
testcase_09 AC 8 ms
9,472 KB
testcase_10 AC 7 ms
9,472 KB
testcase_11 AC 7 ms
9,472 KB
testcase_12 AC 12 ms
9,600 KB
testcase_13 AC 14 ms
9,600 KB
testcase_14 AC 14 ms
9,600 KB
testcase_15 AC 12 ms
9,600 KB
testcase_16 AC 13 ms
9,600 KB
testcase_17 AC 11 ms
9,600 KB
testcase_18 AC 12 ms
9,600 KB
testcase_19 AC 13 ms
9,600 KB
testcase_20 AC 12 ms
9,600 KB
testcase_21 AC 13 ms
9,600 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

import (
	"fmt"
)

func main() {
	var n, m int
	var s, t string
	fmt.Scanf("%d %d", &n, &m)
	fmt.Scanf("%s\n%s", &s, &t)
	answer := findLevenshteinDistance(s, t)
	fmt.Println(answer)
}

func findLevenshteinDistance(s, t string) int {
	//   a b c d e
	// a 0 1 2 3 4
	// d 1 1 2 2 3
	// b 2 1 2 3 3
	var dp [1001][1001]int
	for i := 0; i <= len(s); i++ {
		dp[i][0] = i
	}
	for i := 0; i <= len(t); i++ {
		dp[0][i] = i
	}

	for i := 0; i < len(s); i++ {
		for j := 0; j < len(t); j++ {
			if s[i] == t[j] {
				dp[i+1][j+1] = dp[i][j]
			} else {
				change := dp[i][j] + 1
				delete := dp[i+1][j] + 1
				add := dp[i][j+1] + 1
				changeOrDelete := min(change, delete)
				// fmt.Println("change: ", change, "delete: ", delete, "add: ", add)
				dp[i+1][j+1] = min(changeOrDelete, add)
			}
		}
	}
	// printLimitedTable(dp, len(s), len(t))
	return dp[len(s)][len(t)]
}

func findLcs(s, t string) int {
	//   a b c d e
	// a 1 1 1 1 1
	// d 1 1 1 2 2
	// b 1 2 2 2 2
	var dp [1001][1001]int
	for i := 0; i < len(s); i++ {
		for j := 0; j < len(t); j++ {
			m := max(dp[i+1][j], dp[i][j+1])
			n := dp[i][j]
			if s[i] == t[j] {
				n++
			}
			dp[i+1][j+1] = max(m, n)
		}
	}
	return dp[len(s)][len(t)]
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}

func printLimitedTable(dp [1001][1001]int, n, w int) {
	fmt.Printf("   ")
	for i := 0; i <= w; i++ {
		fmt.Printf("%d ", i)
	}
	fmt.Print("\n")
	for i := 0; i <= n; i++ {
		fmt.Printf("%d: ", i)
		for j := 0; j <= w; j++ {
			fmt.Printf("%d ", dp[i][j])
		}
		fmt.Print("\n")
	}
}
0