zoukankan      html  css  js  c++  java
  • Java for LeetCode 131 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"]
      ]
    解题思路一:

    将s分为左右两个部分,分别求出两边的partition,然后粘一块即可,JAVA实现如下:

    	static public List<List<String>> partition(String s) {
    		Set<List<String>> set = new HashSet<List<String>>();
    		if (isPalindrome(s)) {
    			List<String> alist = new ArrayList<String>();
    			alist.add(s);
    			set.add(alist);
    		}
    		for (int i = 1; i < s.length(); i++) {
    			List<List<String>> left = partition(s.substring(0, i));
    			List<List<String>> right = partition(s.substring(i, s.length()));
    			for (List<String> aLeft : left)
    				for (List<String> aRight : right) {
    					List<String> alist = new ArrayList<String>(aLeft);
    					alist.addAll(aRight);
    					set.add(new ArrayList<String>(alist));
    				}
    		}
    		return new ArrayList<List<String>>(set);
    	}
    
    	static boolean isPalindrome(String s) {
    		int left = 0;
    		int right = s.length() - 1;
    		while (left < right) 
    			if (s.charAt(left++) != s.charAt(right--))
    				return false;
    		return true;
    	}
    

     结果TLE

    解题思路二:

     修改下思路一,从左边入手,如果左边是Palindrome,对右边求一个partition,这样求得的结果也不会重复,这样就可以AC了,JAVA实现如下:

    	static public List<List<String>> partition(String s) {
    		ArrayList<List<String>> list = new ArrayList<List<String>>();
    		if (isPalindrome(s)) {
    			List<String> alist = new ArrayList<String>();
    			alist.add(s);
    			list.add(alist);
    		}
    		for (int i = 1; i < s.length(); i++)
    			if (isPalindrome(s.substring(0, i))) {
    				List<String> aLeft = new ArrayList<String>();
    				aLeft.add(s.substring(0, i));
    				List<List<String>> right = partition(s.substring(i, s.length()));
    				for (List<String> aRight : right) {
    					List<String> alist = new ArrayList<String>(aLeft);
    					alist.addAll(aRight);
    					list.add(new ArrayList<String>(alist));
    				}
    			}
    		return list;
    	}
    
    	static boolean isPalindrome(String s) {
    		int left = 0;
    		int right = s.length() - 1;
    		while (left < right)
    			if (s.charAt(left++) != s.charAt(right--))
    				return false;
    		return true;
    	}
    
  • 相关阅读:
    深度学习中的激活函数
    23.从上往下打印二叉树
    22.栈的压入、弹出序列
    使用TensorFlow实现DNN
    shell按行读取文件
    linux集群批量执行命令
    CDH升级
    自动微分方法(auto diff)
    快速了解负载均衡
    拼写纠错的利器,BK树算法
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4544612.html
Copyright © 2011-2022 走看看