-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpecialStringAgain.cs
111 lines (88 loc) · 2.63 KB
/
SpecialStringAgain.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System.Collections.Generic;
using System.IO;
using System;
class Solution
{
static long SubstrCount(int n, string s)
{
long res = 0;
for (var i = 0; i < n; i++)
{
var chars = new HashSet<char>();
for (var j = 1; j < n - i + 1; j++)
{
var lastChar = s[i + j - 1];
chars.Add(lastChar);
if (j == 1)
{
res++;
continue;
}
if (chars.Count > 2) // has 3 chars, no special
{
break;
}
if (chars.Count == 1) // it could be a or aaa, special
{
res++;
continue;
}
var midSpec = IsMiddleSpecial(s, i, j);
if (midSpec.IsSpecial)
{
res++;
}
if (!midSpec.CanBeSpecial)
{
break;
}
}
}
return res;
}
static MiddleStat IsMiddleSpecial(string text, int pos, int len)
{
if (len % 2 == 0) // even number and aaba, no special
{
return new MiddleStat(false, true);
}
var middleChar = text[pos + len / 2];
var firstChar = text[pos];
if (middleChar == firstChar)
{
return new MiddleStat(false, true);
}
for (int i = 0; i < len / 2; i++)
{
if (text[pos + i] != firstChar) // abaaaa, no special, can not be special in even longer substrings
{
return new MiddleStat(false, false);
}
if (text[pos + len - i - 1] != firstChar)
{
return new MiddleStat(false, true); // aaaba, no special, can be special in longer substrings like aaabaaa
}
}
return new MiddleStat(true, false);
}
private struct MiddleStat
{
public MiddleStat(bool isSpec, bool canBeSpec)
{
IsSpecial = isSpec;
CanBeSpecial = canBeSpec;
}
public bool IsSpecial { get; }
public bool CanBeSpecial { get; }
}
static void Main(string[] args)
{
TextWriter textWriter = new StreamWriter(Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int n = Convert.ToInt32(Console.ReadLine());
string s = Console.ReadLine();
long result = SubstrCount(n, s);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}