mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0131.分割回文串 Rust語言版本
This commit is contained in:
@ -587,5 +587,57 @@ func partition(_ s: String) -> [[String]] {
|
||||
}
|
||||
```
|
||||
|
||||
## Rust
|
||||
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn partition(s: String) -> Vec<Vec<String>> {
|
||||
let mut ret = vec![];
|
||||
let mut path = vec![];
|
||||
let sub_str: Vec<char> = s.chars().collect();
|
||||
|
||||
Self::backtracing(&sub_str, 0, &mut ret, &mut path);
|
||||
|
||||
ret
|
||||
}
|
||||
|
||||
fn backtracing(sub_str: &Vec<char>, start: usize, ret: &mut Vec<Vec<String>>, path: &mut Vec<String>) {
|
||||
//如果起始位置大于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<char>, 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
|
||||
}
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user