-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path131.PalindromePartitioning.cs
85 lines (80 loc) · 2.39 KB
/
131.PalindromePartitioning.cs
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System.Collections.Generic;
using System.Linq;
public class Solution {
public IList<IList<string>> Partition(string s) {
if (s.Length == 0) return new List<IList<string>>();
var paths = new List<int>[s.Length];
for (var i = 0; i < s.Length; ++i)
{
int j, k;
for (j = i, k = i + 1; j >= 0 && k < s.Length; --j, ++k)
{
if (s[j] == s[k])
{
if (paths[k] == null)
{
paths[k] = new List<int>();
}
paths[k].Add(j - 1);
}
else
{
break;
}
}
for (j = i, k = i; j >= 0 && k < s.Length; --j, ++k)
{
if (s[j] == s[k])
{
if (paths[k] == null)
{
paths[k] = new List<int>();
}
paths[k].Add(j - 1);
}
else
{
break;
}
}
}
var prevs = new List<int>[s.Length];
for (var i = 0; i < s.Length; ++i)
{
if (paths[i] != null)
{
foreach (var path in paths[i])
{
if (path < 0 || prevs[path] != null)
{
if (prevs[i] == null)
{
prevs[i] = new List<int>();
}
prevs[i].Add(path);
}
}
}
}
var results = new List<IList<string>>();
var temp = new List<string>();
GenerateResults(prevs, s, s.Length - 1, temp, results);
return results;
}
private void GenerateResults(List<int>[] prevs, string s, int i, IList<string> temp, IList<IList<string>> results)
{
if (i < 0)
{
results.Add(temp.Reverse().ToList());
}
else
{
foreach (var prev in prevs[i])
{
temp.Add(s.Substring(prev + 1, i - prev));
GenerateResults(prevs, s, prev, temp, results);
temp.RemoveAt(temp.Count - 1);
}
}
}
}