我有這樣如何減少這兩種方法的複雜性?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
// returns true or false based on whether s1 and s2 are
// an unordered anagrammatic pair
// e.g. "aac","cac" --> false
// "aac","aca" --> true
// Complexity: O(n)
static bool IsAnagrammaticPair(string s1, string s2)
{
if(s1.Length != s2.Length)
return false;
int[] counter1 = new int[26],
counter2 = new int[26];
for(int i = 0; i < s1.Length; ++i)
{
counter1[(int)s1[i] - (int)'a'] += 1;
counter2[(int)s2[i] - (int)'a'] += 1;
}
for(int i = 0; i < 26; ++i)
if(counter1[i] != counter2[i])
return false;
return true;
}
// gets all substrings of s (not including the empty string,
// including s itself)
// Complexity: O(n^2)
static IEnumerable<string> GetSubstrings(string s)
{
return from i in Enumerable.Range(0, s.Length)
from j in Enumerable.Range(0, s.Length - i + 1)
where j >= 1
select s.Substring(i, j);
}
// gets the number of anagrammatical pairs of substrings in s
// Complexity: O(n^2)
static int NumAnagrammaticalPairs(string s)
{
var substrings = GetSubstrings(s).ToList();
var indices = Enumerable.Range(0, substrings.Count);
return (from i in indices
from j in indices
where i < j && IsAnagrammaticPair(substrings[i], substrings[j])
select 1).Count();
}
static void Main(String[] args)
{
int T = Int32.Parse(Console.ReadLine());
for(int t = 0; t < T; ++t)
{
string line = Console.ReadLine();
Console.WriteLine(NumAnagrammaticalPairs(line));
}
}
}
這是不符合問題的性能基準測試一些代碼。兩個輔助方法我有
GetSubstrings
和
NumAnagrammaticalPairs
我知道是O(n^2)
我在評論中提到的,但是我不知道怎樣才能減少涉及檢索操作的數量回答。有任何想法嗎?
'NumAnagrammaticalPairs'調用'IsAnagrammaticPair',這樣就使得前者爲O(n^3) –
我不認爲你可以減少了'GetSubstrings'&'NumAnagrammaticalPairs'的複雜性。你可以對它們做一些改進,比如使用常規的2嵌套語句而不是使用Linq和枚舉。不知道這是否足夠好 –
或者您可以放棄這兩種方法,一種使用動態規劃的方法。請參閱https://www.topcoder.com/community/data-science/data-science-tutorials/dynamic-programming-from-novice-to-advanced/ –