From 774c3da8309c468f3f12c28c8180fae6403a976d Mon Sep 17 00:00:00 2001 From: YiChih Wang Date: Wed, 5 Jan 2022 22:32:18 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200131.=E5=88=86=E5=89=B2?= =?UTF-8?q?=E5=9B=9E=E6=96=87=E4=B8=B2=20Rust=E8=AA=9E=E8=A8=80=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0131.分割回文串.md | 52 ++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) 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 + } +} +``` -----------------------