Skip to content

Instantly share code, notes, and snippets.

@fengyitsai
Created February 10, 2020 17:32
Show Gist options
  • Save fengyitsai/adca5f4c5a43428f0bc836e576bb6625 to your computer and use it in GitHub Desktop.
Save fengyitsai/adca5f4c5a43428f0bc836e576bb6625 to your computer and use it in GitHub Desktop.
1320. Minimum Distance to Type a Word Using Two Fingers
class Solution {
func minimumDistance(_ word: String) -> Int {
let array = Array(word).compactMap{ $0.asciiValue }.map{ Int($0 - 65) }
var dp = [[Int]](repeating:[Int](repeating:Int.max/2, count:27), count:word.count + 1)
dp[0][26] = 0
for i in 1...word.count {
let current = array[i-1]
let previous = (i == 1) ? 26 : array[i-2]
for c in 0...26 {
dp[i][c] = min(dp[i][c],dp[i-1][c] + distance(previous,current)) // move previous, another stay in c
dp[i][previous] = min(dp[i][previous],dp[i-1][c] + distance(c,current)) // move c, another stay in previous
}
}
return dp[word.count].min()!
}
func distance(_ a:Int, _ b:Int) -> Int {
if a == 26 {
return 0
}
return abs(a/6 - b/6) + abs(a%6 - b%6)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment