fnreverse_in_parens(string:String)->Result<String,String>{letmutchars:Vec<char>=string.chars().collect();letmutstack=Vec::new();foriin0..chars.len(){// need to iterate by index in order to mutate `chars`matchchars[i]{'('=>stack.push(i),')'=>{letfrom_idx=stack.pop().ok_or_else(||format!("Unmached ')' at index {}",i))?;assert!(from_idx<i);lettarget_slice=&mutchars[from_idx+1..i];target_slice.reverse();forcintarget_slice.iter_mut(){*c=match*c{'('=>')',')'=>'(',c=>c,};}}_=>{}}}ifstack.is_empty(){Ok(chars.into_iter().collect())}else{Err(format!("Unmatched '(' at indices {:?}",stack))}}fnmain(){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)");}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Rust: