leetcode

Leetcode problem solutions
git clone https://git.sinitax.com/sinitax/leetcode
Log | Files | Refs | sfeed.txt

lib.rs (1886B)


      1use std::env;
      2use std::str::{self, FromStr};
      3
      4pub trait Parsable {
      5    fn parse(s: &str) -> Self;
      6}
      7
      8impl<T: Parsable> Parsable for Vec<T> {
      9    fn parse(s: &str) -> Vec<T> {
     10        let mut depth = 0;
     11        let mut sep = Vec::new();
     12        let s = s
     13            .trim()
     14            .strip_prefix("[")
     15            .expect("Missing [")
     16            .strip_suffix("]")
     17            .expect("Missing ]");
     18        let mut last = 0;
     19        for (i, c) in s.chars().enumerate() {
     20            if c == '[' {
     21                depth += 1;
     22            } else if c == ']' {
     23                if depth == 0 {
     24                    panic!("Invalid array format");
     25                }
     26                depth -= 1;
     27            } else if c == ',' && depth == 0 {
     28                sep.push((last, i));
     29                last = i + 1;
     30            }
     31        }
     32        if last != s.len() {
     33            sep.push((last, s.len()));
     34        }
     35        let mut out = Vec::new();
     36        for (start, end) in sep {
     37            out.push(parse(s[start..end].trim()));
     38        }
     39        out
     40    }
     41}
     42
     43impl Parsable for i32 {
     44    fn parse(s: &str) -> i32 {
     45        i32::from_str(s).unwrap_or_else(|_| panic!("Failed to parse integer ({s})"))
     46    }
     47}
     48
     49impl Parsable for char {
     50    fn parse(s: &str) -> char {
     51        s.chars()
     52            .next()
     53            .unwrap_or_else(|| panic!("Parsing empty string"))
     54    }
     55}
     56
     57pub fn parse<T: Parsable>(s: &str) -> T {
     58    <T as Parsable>::parse(s)
     59}
     60
     61pub fn vc(s: &str) -> Vec<char> {
     62    parse(s)
     63}
     64
     65pub fn vvc(s: &str) -> Vec<Vec<char>> {
     66    parse(s)
     67}
     68
     69pub fn vi(s: &str) -> Vec<i32> {
     70    parse(s)
     71}
     72
     73pub fn vvi(s: &str) -> Vec<Vec<i32>> {
     74    parse(s)
     75}
     76
     77pub fn arg(n: usize) -> String {
     78    env::args()
     79        .nth(n)
     80        .unwrap_or_else(|| panic!("Failed to get argument ({n})"))
     81}
     82
     83pub fn arg_into<T: Parsable>(n: usize) -> T {
     84    <T as Parsable>::parse(arg(n).as_str())
     85}