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

    Solution:

     1 public class Solution {
     2     public List<List<String>> partition(String s) {
     3         List<List<String>> result=new ArrayList<List<String>>();
     4         List<String> temp=new ArrayList<String>();
     5         dfs(result,temp,s);
     6         return result;
     7     }
     8 
     9     private void dfs(List<List<String>> result, List<String> temp, String s) {
    10         // TODO Auto-generated method stub
    11         if(s.length()==0){
    12             result.add(new ArrayList<String>(temp));
    13             return;
    14         }
    15         for(int i=1;i<=s.length();++i){
    16             String str=s.substring(0, i);
    17             if(isPalindrome(str)){
    18                 temp.add(str);
    19                 dfs(result, temp, s.substring(i));
    20                 temp.remove(temp.size()-1);
    21             }
    22         }    
    23     }
    24 
    25     private boolean isPalindrome(String str) {
    26         // TODO Auto-generated method stub
    27         int end=str.length()-1;
    28         int start=0;
    29         while(start<end){
    30             if(str.charAt(start)!=str.charAt(end))
    31                 return false;
    32             start++;
    33             end--;
    34         }
    35         return true;
    36     }
    37 }
  • 相关阅读:
    Gitee + PicGo搭建图床 & Typora上传图片到图床
    算法思维 ---- 双指针法
    Floyd's cycle-finding algorithm
    Boyer-Moore Voting Algorithm
    youtube-dl 使用小记
    算法思维 ---- 滑动窗口
    Memo
    英语
    BZOJ 3270
    BZOJ 3196
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4096901.html
Copyright © 2011-2022 走看看