如何加快这段代码的速度,将字符添加到字符串中,并将其扩展到所需的长度(所有排列)



我有以下代码:给定一个长度为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,它会运行很长很长的时间。结果似乎是多余的。

因此,问题是如何加快速度并消除这些冗余。

任何建议都将不胜感激。

这是一个非常粗糙的破解,应该会让你开始。

它基本上是通过填充一个字符来向后移动字符串。

static unsafe void performPaddedBubbleSort(string s, char c, int padCount, IList<string> list) {
        s = new string(c, padCount) + s;
        bool complete = false;
        int index = 0;
        int count = 0;
        fixed (char* p = s) {
            while (count < s.Length && *p == c) {
                while (index < s.Length) {
                    if (*(p + index) != c) {
                        // flip them
                        char tempChar = *(p + index);
                        if (index != 0)
                            *((p + index) - 1) = tempChar;
                        *(p + index) = c;
                        list.Add(new string(p));
                    }
                    index++;
                }
                index = 0;
                count++;
            }
        }
    }

填充为3(使其宽度为6个字符)的"ABC"的输入为:

--A-BC
--AB-C
--ABC-
-A-BC-
-AB-C-
-ABC--
A-BC--
AB-C--
ABC---
Elapsed time: 00:00:00.0008663

不确定这是否正是你想要的。。但我想这只是一个开始。正如您所看到的,它在几分之一秒内执行。

最新更新