Участник:Taranov srg/Minimum Distance to Type a Word Using Two Fingers

Материал из DISCOPAL
Перейти к: навигация, поиск

https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers

Python3

 
class Solution:
    def minimumDistance(self, word: str) -> int:
 
        import string
        import numpy as np
 
        def symb_sub_sring_dist(sym, substring, coord):
            return np.sum(np.abs(coord[sym] - coord[substring]), axis=1)
 
 
        n = len(word)
        if n < 3:
            return 0
 
        a = string.ascii_lowercase
        numbers = np.array(list(map(a.find, list(word.lower()))))
        coord = np.array([[i // 6, i % 6] for i in range(len(a))])
        diffs = np.zeros(shape=(2, n))
 
        for i in range(1, n):
            diffs[i % 2, :i] =  diffs[(i-1) % 2, :i] + symb_sub_sring_dist(numbers[i], [numbers[i-1]], coord)
            diffs[i % 2, i] = (diffs[(i-1) % 2, :i] + np.concatenate((np.array([0]), symb_sub_sring_dist(numbers[i], numbers[:i-1], coord)))).min()
        return int(diffs[(n-1) % 2].min())