https://atcoder.jp/contests/abc248/tasks/abc248_a
素直にsetを使う方法も考えましょう。例によってPythonだと、
def F(S): s = set(int(c) for c in S) return next(d for d in range(10) if d not in s)
これをRustにすると、
let set = S.chars().map(|c| (c as i32) - 48).collect::<HashSet<i32>>(); let d = (0..10).filter(|d| !set.contains(d)).next();
RustのsetにはHashSetとBTreeSetがあります。BTreeSetはB木を使っているから、ソートされた列を取り出せます。
iteratorのcollectメソッドって、Vecにするだけじゃなかったんですね。
nextはPythonと同様に最初の項を得ます。ただし、最初の項が無いこともあり得るのでOptionを返します。無かったらNoneを返して、あったらSome(x)を返します。これを取り出すにはmatchを使います。
match d { Some(x) => println!("{}", x), None => (), }
このように、Some(x)とNoneで場合分けできます。
// Lacked Number #![allow(non_snake_case)] use std::collections::HashSet; fn read<T: std::str::FromStr>() -> T { let mut line = String::new(); std::io::stdin().read_line(&mut line).ok(); line.trim().parse().ok().unwrap() } fn main() { let S: String = read(); let set = S.chars().map(|c| (c as i32) - 48).collect::<HashSet<i32>>(); let d = (0..10).filter(|d| !set.contains(d)).next(); match d { Some(x) => println!("{}", x), None => (), } }