Leetcode 131: Palindrome Partitioning

回文字符串分割算法
本文介绍了一种递归算法,用于将输入字符串分割成所有可能的子串组合,确保每个子串都是回文串。通过深度优先搜索(DFS)遍历所有分割可能性,并使用辅助函数检查子串是否为回文。

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

 1 public class Solution {
 2     public IList<IList<string>> Partition(string s) {
 3         var results = new List<IList<string>>();
 4         
 5         DFS(s, 0, new List<string>(), results);
 6         
 7         return results;
 8     }
 9     
10     private void DFS(string s, int start, IList<string> result, IList<IList<string>> results)
11     {
12         if (start >= s.Length)
13         {
14             results.Add(new List<string>(result));
15             return;
16         }
17         
18         for (int i = start; i < s.Length; i++)
19         {
20             var ss = s.Substring(start, i - start + 1);
21             
22             if (IsPalindrome(ss))
23             {
24                 result.Add(ss);
25                 
26                 DFS(s, i + 1, result, results);
27                 
28                 result.RemoveAt(result.Count - 1);
29             }
30         }
31     }
32     
33     private bool IsPalindrome(string s)
34     {
35         if (s.Length <= 1) return true;
36         
37         int i = 0, j = s.Length - 1;
38         while (i < j)
39         {
40             if (s[i] != s[j]) return false;
41             i++;
42             j--;
43         }
44         
45         return true;
46     }
47 }

 

转载于:https://www.cnblogs.com/liangmou/p/7877028.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值