设为首页 加入收藏

TOP

Palindrome Partitioning
2015-07-20 17:42:35 来源: 作者: 【 】 浏览:1
Tags: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"]
  ]

这个题很明显需要DFS,然而实现时犯了一个很大错误。见AC代码。
public class Solution {
    public List
  
   > partition(String s) {
    	List
   
    > res = new ArrayList<>(); List
    
      list = new ArrayList
     
      (); dfs(s, list, res); return res; } public void dfs(String s,List
      
        list,List
       
        > res){ if(s.length()<1){ //巨大错误:!!! 这里必须注意不能写成res.add(list); 因为后面list会改变,导致最终res里面为空 res.add(new ArrayList
        
         (list)); return; } for(int i=0;i
          
          
也可以换种写法思路一样实现有点细微差别:上面是每次改变字符串递归,下面写法是通过下标改变实现字符串变动。
public List
           
            > partition(String s) {
        
		List
            
              item = new ArrayList
             
              (); List
              
               > res = new ArrayList<>(); if(s==null||s.length()==0) return res; dfs(s,0,item,res); return res; } public void dfs(String s, int start, List
               
                 item, List
                
                 > res){ if (start == s.length()){ res.add(new ArrayList
                 
                  (item)); return; } for (int i = start; i < s.length(); i++) { String str = s.substring(start, i+1); if (isPalindrome(str)) { item.add(str); dfs(s, i+1, item, res); item.remove(item.size() - 1); } } } public 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; } }
                 
                
               
              
             
            
           

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇BZOJ 2662 BeiJing wc2012 冻结 下一篇small tree

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·工业机器人TCP校准中 (2025-12-25 05:19:17)
·opc 通讯协议与 TCP (2025-12-25 05:19:15)
·labview中tcp/ip通信 (2025-12-25 05:19:13)
·新书介绍《Python数 (2025-12-25 04:49:47)
·怎么利用 Python 进 (2025-12-25 04:49:45)