这是我今天面试的一个问题:
"给定一个字符串列表,返回一个只有唯一字符串的列表"
我很好奇Skeet认证的答案是什么.
我自己的答案是
public static List<string> sans_repeats ( List<string> input )
{
Dictoinary<string,int> counter = new Dictionary<string,int>();
List<string> output = new List<string>();
foreach ( string S in input )
{
if ( counter.HasKey(S) ) counter[S] = 1;
else ++count[S];
}
foreach ( KeyValuePair<string,int> entry in counter )
if ( entry.Value == 1 ) output.Add(entry.Key);
return output;
}
Run Code Online (Sandbox Code Playgroud)
和采访说
"嗯,这是一种方法......"
在一个听起来居高临下的声音中,好像我做错了什么.
基于更新的问题,这是LINQ的一种方式:
var src = new List<string>() { "dog", "cat", "elephant", "dog", "dog" } ;
src.GroupBy(x => x).Where(y => y.Count() == 1).ToList();
Run Code Online (Sandbox Code Playgroud)