-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path132.PalindromePartitioningII.cs
67 lines (64 loc) · 1.79 KB
/
132.PalindromePartitioningII.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
using System;
using System.Collections.Generic;
public class Solution {
public int MinCut(string s) {
if (s.Length == 0) return 0;
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 partCount = new int[s.Length];
for (var i = 0; i < s.Length; ++i)
{
partCount[i] = int.MaxValue;
if (paths[i] != null)
{
foreach (var path in paths[i])
{
if (path < 0)
{
partCount[i] = 0;
break;
}
else
{
partCount[i] = Math.Min(partCount[i], partCount[path]);
}
}
}
++partCount[i];
}
return partCount[s.Length - 1] - 1;
}
}