https://atcoder.jp/contests/math-and-algorithm/tasks/math_and_algorithm_bp
0からはじめて、(が来たら+1、)が来たら-1として、負になったらアウトです。
// Parentheses Check #![allow(non_snake_case)] //////////////////// library //////////////////// 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 YesNo(b: bool) -> String { return if b { "Yes".to_string() } else { "No".to_string() } } //////////////////// process //////////////////// fn read_input() -> String { let _N: usize = read(); let S = read(); S } fn f(S: String) -> bool { let mut y = 0; for c in S.chars() { match c { '(' => y += 1, ')' => { y -= 1; if y < 0 { return false } }, _ => () } } true } fn main() { let S = read_input(); println!("{}", YesNo(f(S))) }