Hi, I did a random leetcode question with Rust:
Given two strings S
and T
, return if they are equal when both are typed into empty text editors. #
means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c" Output: true Explanation : Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#" Output: true Explanation : Both S and T become "".
And my solution is:
struct Filter(u32);
impl Filter {
fn new() -> Self {
Filter(0)
}
fn filter(&mut self, c: &char) -> bool {
if c == &'#' {
self.0 += 1;
false
} else {
if self.0 == 0 {
true
} else {
self.0 -= 1;
false
}
}
}
}
fn backspace_compare(s: String, o: String) -> bool {
let mut s_filter = Filter::new();
let mut last_s_iter = s.chars().rev().filter(|c| s_filter.filter(c));
let mut o_filter = Filter::new();
let mut last_o_iter = o.chars().rev().filter(|c| o_filter.filter(c));
loop {
let last_s = last_s_iter.next();
let last_o = last_o_iter.next();
if last_s != last_o {
return false;
}
if last_s.is_none() {
break;
}
}
return true;
}
The performance was good enough. But I'm wondering can these codes be simpler. Like using closure or using Iterator instead of the loop. I tried to use closure instead of the struct, but failed because of the lifetime:
fn get_filter() -> impl FnMut(&char)->bool{
let mut bs_counter=0; //bs_counter not live long enough. And I don't know how to add lifetime to this...
|c|{
if c == &'#' {
bs_counter += 1;
false
} else {
if bs_counter == 0 {
true
} else {
bs_counter -= 1;
false
}
}
}
}
Just want to know the best practice of these, thank you very much!