Skip to content

Commit 6de5da7

Browse files
Merge pull request youngyangyang04#995 from andywang0607/131_rust
添加 0131.分割回文串 Rust語言版本
2 parents a47643d + 774c3da commit 6de5da7

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

problems/0131.分割回文串.md

+52
Original file line numberDiff line numberDiff line change
@@ -587,5 +587,57 @@ func partition(_ s: String) -> [[String]] {
587587
}
588588
```
589589

590+
## Rust
591+
592+
```rust
593+
impl Solution {
594+
pub fn partition(s: String) -> Vec<Vec<String>> {
595+
let mut ret = vec![];
596+
let mut path = vec![];
597+
let sub_str: Vec<char> = s.chars().collect();
598+
599+
Self::backtracing(&sub_str, 0, &mut ret, &mut path);
600+
601+
ret
602+
}
603+
604+
fn backtracing(sub_str: &Vec<char>, start: usize, ret: &mut Vec<Vec<String>>, path: &mut Vec<String>) {
605+
//如果起始位置大于s的大小,说明找到了一组分割方案
606+
if start >= sub_str.len() {
607+
ret.push(path.clone());
608+
return;
609+
}
610+
611+
for i in start..sub_str.len() {
612+
if !Self::is_palindrome(sub_str, start, i) {
613+
continue;
614+
}
615+
//如果是回文子串,则记录
616+
let s: String = sub_str[start..i+1].into_iter().collect();
617+
path.push(s);
618+
619+
//起始位置后移,保证不重复
620+
Self::backtracing(sub_str, i+1, ret, path);
621+
path.pop();
622+
}
623+
624+
}
625+
626+
fn is_palindrome(s: &Vec<char>, start: usize, end: usize) -> bool {
627+
let (mut start, mut end) = (start, end);
628+
629+
while start < end {
630+
if s[start] != s[end] {
631+
return false;
632+
}
633+
634+
start += 1;
635+
end -= 1;
636+
}
637+
638+
true
639+
}
640+
}
641+
```
590642
-----------------------
591643
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)