LeetCode 1138. Alphabet Board Path

Problem Statement


use std::collections::HashMap;

impl Solution {
pub fn alphabet_board_path(target: String) -> String {
let mut map: HashMap<char, (i32, i32)> = HashMap::new();
let alphabet: Vec<char> = "abcdefghijklmnopqrstuvwxyz".chars().collect();
for i in 0..26 {
map.insert(alphabet[i], (i as i32 / 5, i as i32 % 5));
}
let (mut t, mut ans, mut dx, mut dy) : (String, String, i32, i32) = (
target.clone(), "".to_string(), 0, 0);
t.insert(0, 'a');

for i in 1..t.len() {
let (cur, prev) = (map.get(&t.chars().nth(i).unwrap()).unwrap(),
map.get(&t.chars().nth(i - 1).unwrap()).unwrap());
dx = cur.0 - prev.0; dy = cur.1 - prev.1;
if dy < 0 {
ans.push_str(&(0..dy * -1).map(|_| "L").collect::<String>());
}
if dx < 0 {
ans.push_str(&(0..dx * -1).map(|_| "U").collect::<String>());
}
if dy > 0 {
ans.push_str(&(0..dy).map(|_| "R").collect::<String>());
}
if dx > 0 {
ans.push_str(&(0..dx).map(|_| "D").collect::<String>());
}
ans.push('!');
}
return ans;
}
}