rustgym/leetcode/
_1165_single_row_keyboard.rs1struct Solution;
2
3impl Solution {
4 fn calculate_time(keyboard: String, word: String) -> i32 {
5 let mut indexes: Vec<i32> = vec![0; 26];
6 for (i, b) in keyboard.bytes().enumerate() {
7 indexes[(b - b'a') as usize] = i as i32;
8 }
9 let mut prev = 0;
10 let mut sum = 0;
11 for b in word.bytes() {
12 let index = indexes[(b - b'a') as usize];
13 sum += (index - prev).abs();
14 prev = index;
15 }
16 sum
17 }
18}
19
20#[test]
21fn test() {
22 let keyboard = "abcdefghijklmnopqrstuvwxyz".to_string();
23 let word = "cba".to_string();
24 assert_eq!(Solution::calculate_time(keyboard, word), 4);
25 let keyboard = "pqrstuvwxyzabcdefghijklmno".to_string();
26 let word = "leetcode".to_string();
27 assert_eq!(Solution::calculate_time(keyboard, word), 73);
28}