我正在做一道家庭作业问题,要求不使用框架方法来分割字符串。
下面是我想出来的可行代码。
我想知道如何将运行时间提高到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);
}
if(buff.Length != 0)
是为了将未处理完的缓冲区写入结果。 - Nemo