forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path131-Palindrome-Partitioning.cs
More file actions
46 lines (39 loc) · 928 Bytes
/
131-Palindrome-Partitioning.cs
File metadata and controls
46 lines (39 loc) · 928 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Solution
{
//O(N.2^N)
public IList<IList<string>> Partition(string s)
{
var result = new List<IList<string>>();
var stack = new List<string>();
void dfs(int i)
{
if (i >= s.Length)
{
result.Add(stack.ToList());
return;
}
for (var j = i; j < s.Length; j++)
{
if (IsPalindrome(s, i, j))
{
stack.Add(s.Substring(i, j - i + 1));
dfs(j + 1);
stack.RemoveAt(stack.Count - 1);
}
}
}
dfs(0);
return result;
}
public bool IsPalindrome(string s, int l, int r)
{
while (l < r)
{
if (s[l] != s[r])
return false;
l++;
r--;
}
return true;
}
}