我最近进行了在线挑战,并被要求查找所有连续chars
的数字,它是对称的。
e.g。 02002
会提供以下内容
3 x 0
,2 x 2
(单个数字是对称的)
1 x 00
020
,200
,002
(最后2个可以重新排序到020
)
2002
02002
- 可以重新订购到20002
或02020
(但计为1)
我已经提出了以下解决方案,但它被标记为not scaleable
(假设因为它是O(n + 1C2)[n + 1 选择 r]而不是O (n)的
确实说过这个问题有一个O(n)解决方案(我纯粹是一个可以验证输出的aciton方法)
public int TotalCombinations(string S)
{
var sum = 0;
FindCombinations(S, (s, i, arg3) => sum++);
return sum;
}
public void FindCombinations(string S, Action<string, int, int> action)
{
var singles = new HashSet<char>();
var comparisons = 0;
for (int i = 0; i < S.Length; i++)
{
singles.Clear();
for (int j = i; j >= 0; j--)
{
var val = S[j];
if (singles.Contains(val))
singles.Remove(val);
else singles.Add(val);
if (singles.Count <= 1)
action(S, j, i);
comparisons++;
}
}
Console.WriteLine($"{S.Length} = {comparisons}");
}
我创建了一些测试:
[TestFixture]
public class DemoTest
{
[Test]
[TestCase("0",1)]
[TestCase("5",1)]
[TestCase("00",3)]
[TestCase("002",5)]
[TestCase("0202",7)]
[TestCase("02002",11)]
[TestCase("020028",13)]
[TestCase("0200282",16)]
public void DemoTest1_1(string input, int expected)
{
var test = new Solution();
var res = test.TotalCombinations(input);
res.Should().Be(expected);
}
[Test]
public void ExampleOutput()
{
var res = new List<string>();
var test = new Solution();
Action<string, int, int> action = (s, from, to) =>
res.Add(s.Substring(@from, to - @from + 1));
test.FindCombinations("02002", action);
res.Should().BeEquivalentTo("0", "0", "0", "2", "2", "00", "020", "200", "002", "2002", "02002");
foreach (var v in res)
{
Console.WriteLine(v + ", ");
}
}
}