c# – 没有string的分裂字符串.Split

c# – 没有string的分裂字符串.Split,第1张

概述我正在做一个家庭工作问题,不使用框架方法拆分字符串. 以下是我提出的工作代码. 我想知道如何改善O(n)的运行时间? 此外,欢迎任何改进建议. public static string[] split(string txt, char[] delim){ char[] text = txt.ToCharArray(); string[] result = new string[0 我正在做一个家庭工作问题,不使用框架方法拆分字符串.

以下是我提出的工作代码.

我想知道如何改善O(n)的运行时间?

此外,欢迎任何改进建议.

public static string[] split(string txt,char[] delim){    char[] text = txt.tochararray();    string[] result = new string[0];    int count = 0;    int i = 0;    StringBuilder buff = new StringBuilder();     while(i < text.Length)    {        bool found = false;        foreach(char del in delim)        {            if(del == txt[i])            {                found = true;                break;            }        }        if(found)        {            count++;            Array.Resize(ref result,count);            result[count - 1] = buff.ToString();            buff = new StringBuilder();                         }        else        {            buff.Append(txt[i]);        }        i++;    }    if(buff.Length != 0)    {        count++;        Array.Resize(ref result,count);        result[count - 1] = buff.ToString();    }    return(result);}
解决方法 我有一些更改会同时使这个函数更像C,并将运行时间减少到O(n):

1)你应该多次动态调整结果数组的大小,而不是动态地调整结果数组的大小,而应该创建足够的点来保存最大数量的字符串(你知道这个数字小于txt.Length),然后在最后一次调整它的大小.归还它.

2)不要使用StringBuilder组合你的结果,而是制作长度为txt.Length且索引变量为j的char [] buff并执行buff [j] = txt [i].

我认为你的功能应该是O(N).从技术上讲,它将是O(N * M),其中M是分隔符的数量.

编辑1:

这是一个改变,它将使O(N)O(M)而不是O(N * M):

您应该循环遍历ADVANCE中的分隔符并设置如下所示的数组,而不是循环遍历字符串中每个字符的分隔符:

bool[] isDelimiter = new bool[128];  // increase size if you are allowing non-asciiforeach(char delim in isDelimiter){    isDelimiter[(int)char] = true;}

然后你可以使用这个数组在恒定时间内测试字符串的每个字符.

总结

以上是内存溢出为你收集整理的c# – 没有string的分裂字符串.Split全部内容,希望文章能够帮你解决c# – 没有string的分裂字符串.Split所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1248438.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存