zoukankan      html  css  js  c++  java
  • [leetcode] Palindrome Partitioning

    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"]
      ]

    https://oj.leetcode.com/problems/palindrome-partitioning/

    思路:因为要返回所有的结果,dfs来做。

    public class Solution {
        public List<List<String>> partition(String s) {
            List<List<String>> res = new ArrayList<List<String>>();
            if (s == null || s.length() == 0)
                return res;
            List<String> tmp = new ArrayList<String>();
            part(res, tmp, s);
    
            return res;
        }
    
        private void part(List<List<String>> res, List<String> tmp, String s) {
            if ("".equals(s)) {
                res.add(new ArrayList(tmp));
                return;
            }
            for (int i = 1; i <= s.length(); i++) {
                String pre = s.substring(0, i);
                if (isPalin(pre)) {
                    tmp.add(pre);
                    part(res, tmp, s.substring(i, s.length()));
                    tmp.remove(tmp.size()-1);
                }
            }
    
        }
    
        private boolean isPalin(String s) {
            if (s == null)
                return false;
            if (s.length() <= 1)
                return true;
            int len = s.length();
            int i = 0, j = len - 1;
            while (i < j) {
                if (s.charAt(i++) != s.charAt(j--))
                    return false;
            }
            return true;
    
        }
    
        public static void main(String[] args) {
            System.out.println(new Solution().partition("aab"));
        }
    }

    参考:

    http://www.tuicool.com/articles/jmQ3uu

    http://blog.csdn.net/worldwindjp/article/details/22066307

  • 相关阅读:
    内置函数详解
    lambda函数
    第八章(5)
    第八章(4)
    第八章(3)
    第八章(2)
    第八章(1)
    第七章(3)
    第七章(2)
    第七章(1)
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3828791.html
Copyright © 2011-2022 走看看