offer2-86


给定一个字符串 s ,请将 s 分割成一些子串,使每个子串都是 回文串 ,返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

示例 1:

输入:s = "google"
输出:[["g","o","o","g","l","e"],["g","oo","g","l","e"],["goog","l","e"]]

示例 2:

输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 3:

输入:s = "a"
输出:[["a"]]

提示:

  • 1 <= s.length <= 16
  • s 仅由小写英文字母组成

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {

    public String[][] partition(String s) {
        if (s == null || s.length() == 0) {
            return new String[0][0];
        }
        boolean[][] symmetry = new boolean[s.length()][s.length()];
        for (int i = 0; i < s.length(); i++) {
            symmetry[i][i] = true;
        }

        for (int i = 0; i < s.length() - 1; i++) {
            for (int j = i + 1; j < s.length(); j++) {
                if (isSymmetry(s, i, j)) {
                    symmetry[i][j] = true;
                }
            }
        }

        List<String[]> result = new ArrayList<>();
        doPartition(result, symmetry, new ArrayList<>(), s);
        return result.toArray(new String[result.size()][]);
    }

    private void doPartition(List<String[]> result, boolean[][] symmetry, List<Integer> curList, String s) {
        int lastEnd = curList.size() == 0 ? -1 : curList.get(curList.size() - 1);

        if (lastEnd == s.length() - 1) {
            String[] one = new String[curList.size()];
            int last = -1;

            for (int i = 0; i < curList.size(); i++) {
                one[i] = s.substring(last + 1, curList.get(i) + 1);
                last = curList.get(i);
            }

            result.add(one);
            return;
        }

        int start = lastEnd + 1;
        for (int j = start; j < s.length(); j++) {
            if (symmetry[start][j]) {
                curList.add(j);
                doPartition(result, symmetry, curList, s);
                curList.remove(curList.size() - 1);
            }
        }
    }


    private boolean isSymmetry(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }

        return true;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !