LeetCode 1165. Single-Row Keyboard

Problem Statement


use std::collections::HashMap;

impl Solution {
pub fn calculate_time(keyboard: String, word: String) -> i32 {
let mut map = HashMap::new();
for i in 0..26 {
map.insert(keyboard.chars().nth(i).unwrap(), i);
}

let (mut ans, size) = (0, word.len());
if size == 1 {
return ans;
}

for i in 0..size {
let ci = word.chars().nth(i).unwrap();
if i == 0 {
ans += *map.get(&ci).unwrap() as i32;
continue;
}
let cii = word.chars().nth(i - 1).unwrap();
ans += (*map.get(&cii).unwrap() as i32
- *map.get(&ci).unwrap() as i32).abs();
}
return ans;
}
}