Skip to content

Instantly share code, notes, and snippets.

@frol
Created March 2, 2019 21:53
Show Gist options
  • Select an option

  • Save frol/c9294acc26f2f9c6d02e9c428dd6a1a5 to your computer and use it in GitHub Desktop.

Select an option

Save frol/c9294acc26f2f9c6d02e9c428dd6a1a5 to your computer and use it in GitHub Desktop.
/// This is a direct line-by-line translation from C++ solution:
/// https://github.com/LyashenkoGS/cpluplus_study/blob/master/test/Solution.cpp
///
/// The point is to show that Rust can save your ass.
struct Solution {}
impl Solution {
fn processParenthesis(stack1: &mut Vec<char>, item: char, openSign: char, closingSign: char) {
if item == openSign {
stack1.push(item);
} else if item == closingSign {
let top = stack1.last();
if top == openSign { // Rust produces a compilation error here:
// ^^^^^^^^ expected enum `std::option::Option`, found char
// = note: expected type `std::option::Option<&char>`
// found type `char`
//
// This means that `stack1.last()` returns either the last value or None,
// and we MUST handle this case in our code. Here is a naive approach, we
// assume that None will never occur and we just force Rust to get the
// last value:
// if *top.unwrap() == openSign {
//
// Rust will agree to compile this code, but it may now get into the runtime error:
// 10: qq4::Solution::processParenthesis
// at src/main.rs:14
// 11: qq4::Solution::isValid
// at src/main.rs:43
// 12: qq4::mytest
// at src/main.rs:56
//
// I hope you can get the root cause of the error.
stack1.pop();
}
}
}
fn isValid(s: &str) -> bool {
let mut stack = Vec::new();
for item in s.chars() {
Self::processParenthesis(&mut stack,item,'(',')');
Self::processParenthesis(&mut stack,item,'[',']');
Self::processParenthesis(&mut stack,item,'{','}');
}
return stack.is_empty();
}
}
#[test]
fn mytest() {
assert!(Solution::isValid("[]"));
assert!(Solution::isValid("[]()"));
assert!(Solution::isValid("[]{}()"));
assert!(Solution::isValid("))"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment