-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
64 lines (61 loc) · 1.8 KB
/
Program.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
//利用二分搜索。
using System;
using System.Collections.Generic;
namespace LongestRepeatingSubstring
{
class Program
{
static void Main(string[] args)
{
// 012345678910
string S = "aaaaa";
//Console.WriteLine(SearchLength(4, S));
Console.WriteLine(LongestRepeatingSubstring_BinarySearch(S));
}
static int LongestRepeatingSubstring_BruteForce(string S)
{
var res = 0;
var candidates = new HashSet<string>();
for (int i = 0; i < S.Length; i++)
{
for (int j = 1; j <= S.Length - i; j++)
{
string temp = S.Substring(i, j);
if (candidates.Contains(temp))
res = Math.Max(res, temp.Length);
else
candidates.Add(temp);
}
}
return res;
}
static int LongestRepeatingSubstring_BinarySearch(string S)
{
int li = 0, hi = S.Length, res = 0;
while (li < hi)
{
int mid = li + (hi - li) / 2;
if (!SearchLength(mid, S))
hi = mid;
else
{
li = mid + 1;
res = Math.Max(res, mid);
}
}
return res;
}
static bool SearchLength(int len, string S)
{
var set = new HashSet<string>();
for (int i = 0; i <= S.Length - len; i++)
{
string temp = S.Substring(i, len);
if (set.Contains(temp))
return true;
set.Add(temp);
}
return false;
}
}
}