我正在准备面试技术测试,我遇到了这个问题:
在不使用缓冲区的情况下删除字符串中的所有重复项,允许使用 1 或 2 个附加变量。
我想知道在执行以下操作时,我是否使用缓冲区?谢谢。
static void Main(string[] args)
{
string temp = "amanisaman";
temp = noDups(temp);
MessageBox.Show(temp);
}
public string noDups(string word)
{
string table = "";
foreach (var character in word)
{
if (table.IndexOf(character) == -1)
{
table += character; // would this count as a buffer storage?
}
}
return table;
}
Run Code Online (Sandbox Code Playgroud)
使用 LINQ...
这假设您的临时字符串并且您想要删除这些字符。
string originalString = "amanisaman";
string newString = string.Join(" ", originalString.ToCharArray().Distinct());
Run Code Online (Sandbox Code Playgroud)
这假设您要删除重复的单词。
string originalString = "this is my test string here, this test";
string newString = string.Join(" ", originalString.Split(new Char[] {' '}).Distinct());
Run Code Online (Sandbox Code Playgroud)