From 508bf989fcdf9acb938a752b02ab6738d7d10a03 Mon Sep 17 00:00:00 2001 From: whai Date: Sun, 18 Feb 2024 09:03:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E6=BA=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leetCode/BackTracking/LeetCode131.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/main/java/cn/whaifree/leetCode/BackTracking/LeetCode131.java diff --git a/src/main/java/cn/whaifree/leetCode/BackTracking/LeetCode131.java b/src/main/java/cn/whaifree/leetCode/BackTracking/LeetCode131.java new file mode 100644 index 0000000..84f0c12 --- /dev/null +++ b/src/main/java/cn/whaifree/leetCode/BackTracking/LeetCode131.java @@ -0,0 +1,71 @@ +package cn.whaifree.leetCode.BackTracking; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * @version 1.0 + * @Author whai文海 + * @Date 2024/2/10 15:12 + * @注释 + */ +public class LeetCode131 { + + @Test + public void test() { + String abbc = "aaab"; + new Solution().partition(abbc).forEach( + list -> { + System.out.println(list); + } + ); + } + + class Solution { + + List> res = new ArrayList<>(); + List path = new ArrayList<>(); + public List> partition(String s) { + backTracking(s, 0); + return res; + } + + /** + * 1. 判断回文字符串函数
+ * 2. 从start开始切割,到i i++
+ * 递归 + * + * + * @param s + * @param start + */ + public void backTracking(String s, int start) { + if (start >= s.length()) { + res.add(new ArrayList<>(path)); + return; + } + for (int i = start; i < s.length(); i++) { + if (isPalindrome(s, start, i)) { + String substring = s.substring(start, i + 1); + path.add(substring); + backTracking(s, i + 1); + path.remove(path.size() - 1); + } + } + + } + + //判断是否是回文串 + 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; + } + } +}