DEV Community

Discussion on: Daily Challenge #151 - Reverse Parentheses

Collapse
 
idanarye profile image
Idan Arye

Rust:

fn reverse_in_parens(string: String) -> Result<String, String> {
    let mut chars: Vec<char> = string.chars().collect();
    let mut stack = Vec::new();
    for i in 0..chars.len() {  // need to iterate by index in order to mutate `chars`
        match chars[i] {
            '(' => stack.push(i),
            ')' => {
                let from_idx = stack.pop().ok_or_else(|| format!("Unmached ')' at index {}", i))?;
                assert!(from_idx < i);
                let target_slice = &mut chars[from_idx + 1..i];
                target_slice.reverse();
                for c in target_slice.iter_mut() {
                    *c = match *c {
                        '(' => ')',
                        ')' => '(',
                        c => c,
                    };
                }
            }
            _ => {}
        }
    }
    if stack.is_empty() {
        Ok(chars.into_iter().collect())
    } else {
        Err(format!("Unmatched '(' at indices {:?}", stack))
    }
}

fn main() {
    assert_eq!(reverse_in_parens("one (ruof ((rht)ee) owt)".to_owned()).unwrap(), "one (two ((thr)ee) four)");
    assert_eq!(reverse_in_parens("one (two (three) four)".to_owned()).unwrap(), "one (ruof (three) owt)");
}