Skip to content

Commit

Permalink
添加0131.分割回文串 Java版本
Browse files Browse the repository at this point in the history
  • Loading branch information
nanhuaibeian committed May 13, 2021
1 parent 231baca commit b38296b
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions problems/0131.分割回文串.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,46 @@ public:
Java:
```Java
class Solution {
List<List<String>> lists = new ArrayList<>();
Deque<String> deque = new LinkedList<>();
public List<List<String>> partition(String s) {
backTracking(s, 0);
return lists;
}
private void backTracking(String s, int startIndex) {
//如果起始位置大于s的大小,说明找到了一组分割方案
if (startIndex >= s.length()) {
lists.add(new ArrayList(deque));
return;
}
for (int i = startIndex; i < s.length(); i++) {
//如果是回文子串,则记录
if (isPalindrome(s, startIndex, i)) {
String str = s.substring(startIndex, i + 1);
deque.addLast(str);
} else {
continue;
}
//起始位置后移,保证不重复
backTracking(s, i + 1);
deque.removeLast();
}
}
//判断是否是回文串
private boolean isPalindrome(String s, int startIndex, int end) {
for (int i = startIndex, j = end; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}
```

Python:

Expand Down

0 comments on commit b38296b

Please sign in to comment.