• 131. Palindrome Partitioning


        /*
         * 131. Palindrome Partitioning 
         * 2015-12-17 by Mingyang 
         * Return all possible palindrome partitioning of s.
         * 1.长度标准:无(固定)
         * 2.可选的范围:从start开始到最后一个
         * 3.往前走一步:temp加入这个数,然后start加1表示从下一位加起
         * 4.后退一步:temp减去这个数
         * 5.特别的case:start到最后一位
         * 6.关于重复:无
         * 这个题目自己最开始做的时候没有加start这个参数,每次把没用完的string截取下来继续往前传
         * 但是更好的是用一个start index(这样不会把string截取来截取去的)
         */
        public List<List<String>> partition(String s) {
            List<String> item = new ArrayList<String>();
            List<List<String>> res = new ArrayList<List<String>>();
            if (s == null || s.length() == 0)
                return res;
            dfs(s, 0, item, res);
            return res;
        }
        public void dfs(String s, int start, List<String> item,List<List<String>> res) {
            if (start == s.length()) {
                res.add(new ArrayList<String>(item));
                return;
            }
            for (int i = start; i < s.length(); i++) {
                String str = s.substring(start, i + 1);// 每一轮dfs进来都是先取第一个数,start index,可以不用stringbuffer来存
                if (isPalindrome(str)) {
                    item.add(str);
                    dfs(s, i + 1, item, res);// 上面取到i,所以下一个start index就是i+1
                    item.remove(item.size() - 1);
                }
            }
        }
        public static boolean isPalindrome(String s) {
            int low = 0;
            int high = s.length() - 1;
            while (low < high) {
                if (s.charAt(low) != s.charAt(high))
                    return false;
                low++;
                high--;
            }
            return true;
        }
  • 相关阅读:
    机器学习手稿--NumPy篇
    机器学习手稿--PyTorch篇
    算法相关库
    如何保存用户的登录状态
    Go开发新手需知:Printf、Sprintf、Println 的区别
    二、Bean生命周期中AOP的流程
    Spring 注解驱动开发-IOC (精华版)
    我是如何编写流程图程序的?
    微前端架构设计之 WebSocket API 断连后重连的设计方案
    工具-使用distinct方法去重对象List
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5518570.html
Copyright © 2020-2023  润新知