我有以下代码:给定一个长度为 m 的字符串,将“-”添加到任何可能的位置(包括原始字符串的不同字符之间)以将其扩展到长度 n。例如,给定“ABC”,将其扩展为 6。它将是“---ABC”、“--A-BC”、“--AB-C”、“--ABC-”、...。 ..,“AB---C”,“ABC---”。
class Program
{
// <summary>
/// Grow a string to desired length with time limitation
/// </summary>
/// <param name="s"></param>
/// <param name="length"></param>
/// <param name="pad"></param>
/// <param name="Padded"></param>
public static bool ExtendToLen(string s, int length, char pad, ref List<string> Padded, ref Stopwatch timer, int timeOut)
{
if (s.Length == length)
{
Padded.Add(s);
return true;
}
else if (s.Length > length)
{
return true;
}
else
{
List<int> pos = GetExceptPos(s, pad.ToString());
pos.Sort();
int count = -1;
foreach (int p in pos)
{
if (timer.Elapsed.TotalSeconds > timeOut)
{
return false;
}
//Debug.WriteLine(string.Format("pos:{0}", p), "PadToLength");
count++;
// Pad left
string leftPadStr = s.Substring(0, p) + pad + s.Substring(p);
//Debug.WriteLine(string.Format("\tLeftPadStr:{0}", leftPadStr));
bool go = ExtendToLen(leftPadStr, length, pad, ref Padded, ref timer, timeOut);
if (go == false) { return false; }
// Pad right at the last pos
if (count == pos.Count - 1)
{
string rightPadStr = s + pad;
go = ExtendToLen(rightPadStr, length, pad, ref Padded, ref timer, timeOut);
if (go == false) { return false; }
}
}
return true;
}
}
/// <summary>
/// Find indexes of elements different from target str
/// </summary>
/// <param name="str"></param>
/// <param name="excludeStr"></param>
/// <returns></returns>
private static List<int> GetExceptPos(string str, string excludeStr)
{
List<int> allIndexes = new List<int>();
for (int i = 0; i < str.Length; i++)
{
allIndexes.Add(i);
}
return allIndexes.Except(str.IndexesOf(excludeStr)).ToList();
}
static void Main(string[] args)
{
string old = "ACGUA";
List<string> newList = new List<string>();
Stopwatch timer = new Stopwatch();
timer.Start();
bool isGood = ExtendToLen(old, 12, '-', ref newList, ref timer, 100);
timer.Stop();
foreach (string s in newList)
{
Console.WriteLine(s);
}
Console.WriteLine("Elapsed time: {0}", timer.Elapsed);
Console.ReadLine();
}
}
public static class ExtensionMethods
{
/// <summary>
/// Return all indeces
/// </summary>
/// <param name="haystack"></param>
/// <param name="needle"></param>
/// <returns></returns>
public static IEnumerable<int> IndexesOf(this string haystack, string needle)
{
int lastIndex = 0;
while (true)
{
int index = haystack.IndexOf(needle, lastIndex);
if (index == -1)
{
yield break;
}
yield return index;
lastIndex = index + needle.Length;
}
}
}
它运行缓慢,例如,如果我想将一个字符串 (len = 5) 扩展到 20,它会运行 long long long time。结果似乎是多余的。
所以问题是如何加快速度并消除这些冗余。
任何建议将不胜感激。