【Java力扣算法】LeetCode 131 分割回文串

题目:

      分割回文串
      给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
      返回 s 所有可能的分割方案。
示例:
       输入: "aab"
       输出:
       [
         ["aa","b"],
         ["a","a","b"]
       ]

 

【Java力扣算法】LeetCode 131 分割回文串_第1张图片

 

代码:

 

class Go{
    List> result = new ArrayList<>();
    List list = new ArrayList<>();
    char[] arr;
    String s;
    void core(int index){
        if (index == arr.length){
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = index; i < arr.length; i++){
            if (ishw(index,i)){
                list.add(s.substring(index,i + 1));
                core(i + 1);
                list.remove(list.size() - 1);
            }
        }
    }
    boolean ishw(int left,int right){
        int L = left,R = right;
        while (L <= R){
            if (arr[L++] != arr[R--]){
                return false;
            }
        }
        return true;
    }
    public List> partition(String s) {
        arr = s.toCharArray();
        this.s = s;
        core(0);
        return result;
    }
}
public class Cutpalindrome {
    public static void main(String[] args) {
        Go g = new Go();
        System.out.println(g.partition("aacb"));
    }
}

 

你可能感兴趣的:(java算法习题程序)