LeetCode 1055. Shortest Way to Form String

Problem Statement


use std::collections::HashMap;


use std::collections::HashSet;

impl Solution {
pub fn shortest_way(source: String, target: String) -> i32 {
let (ss, st, mut ans) = (source.len(), target.len(), 1);
let mut set = HashSet::new();
for c in source.chars() {
set.insert(c);
}
let (mut i, mut j) = (0, 0);
while i < st {
if !set.contains(&target.chars().nth(i).unwrap()) {
return -1;
}
while j < ss && source.chars().nth(j).unwrap()
!= target.chars().nth(i).unwrap() {
j += 1;
}
if j == ss {
j = 0; i -= 1; ans += 1;
} else {
j += 1;
}
i += 1;
}

return ans;
}
}