diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index ec8ad61c..439ad8ea 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -587,5 +587,57 @@ func partition(_ s: String) -> [[String]] { } ``` +## Rust + +```rust +impl Solution { + pub fn partition(s: String) -> Vec> { + let mut ret = vec![]; + let mut path = vec![]; + let sub_str: Vec = s.chars().collect(); + + Self::backtracing(&sub_str, 0, &mut ret, &mut path); + + ret + } + + fn backtracing(sub_str: &Vec, start: usize, ret: &mut Vec>, path: &mut Vec) { + //如果起始位置大于s的大小,说明找到了一组分割方案 + if start >= sub_str.len() { + ret.push(path.clone()); + return; + } + + for i in start..sub_str.len() { + if !Self::is_palindrome(sub_str, start, i) { + continue; + } + //如果是回文子串,则记录 + let s: String = sub_str[start..i+1].into_iter().collect(); + path.push(s); + + //起始位置后移,保证不重复 + Self::backtracing(sub_str, i+1, ret, path); + path.pop(); + } + + } + + fn is_palindrome(s: &Vec, start: usize, end: usize) -> bool { + let (mut start, mut end) = (start, end); + + while start < end { + if s[start] != s[end] { + return false; + } + + start += 1; + end -= 1; + } + + true + } +} +``` -----------------------