LeetCode每日一题:回文字符串 1

问题描述

Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s ="aab",
Return
[
["aa","b"],
["a","a","b"]
]

问题分析

这题考察把字符串s分割成更小的子串,其中所有的子串都满足是回文子串。
这题最好使用递归地方式进行求解:

  1. 首先计算string.substring(0,i)是否是回文的,若是回文的,则计算string.substring(i)是否是回文,采用递归地思想直到string.length()为0,若其中出现了不是回文的字符串,则i=i+1
  2. 将每次分解的结果存在list里
  3. 将list存在result中,就可以得到结果了

代码实现

public ArrayList> partition(String s) {
        ArrayList> result = new ArrayList>();
        ArrayList list = new ArrayList();//存储当前一种切割的结果
        if (s.length() == 0) return result;
        getPartition(result, list, s);
        return result;
    }

    private void getPartition(ArrayList> result, ArrayList list, String string) {
        if (string.length() == 0) result.add(new ArrayList(list));
        //如果string长度为0了,说明这种切分满足都是回文,将这种切分的结果list加入到result中
        int len = string.length();
        for (int i = 1; i <= len; i++) {
            String str = string.substring(0, i);
            if (isPartition(str)) {
                list.add(str);
                getPartition(result, list, string.substring(i));//传入i之后的继续切割
                list.remove(list.size() - 1);//不加这句通不过AC,因为最后一个会是string本身
            }
        }
    }

    private boolean isPartition(String string) {//判断是否是回文数
        int i = 0;
        int j = string.length() - 1;
        while (i < j) {
            if (string.charAt(i) != string.charAt(j)) return false;
            i++;
            j--;
        }
        return true;
    }

你可能感兴趣的:(LeetCode每日一题:回文字符串 1)