且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

编程挑战:如何检查列表中的所有元素是否唯一

更新时间:2023-11-28 16:16:04

一个更简单的解决方案是对所有基于字符串的数字进行排序。

此时,任何包含另一个数字的数字将立即出现在列表中。

A simpler solution is to sort all the string-based numbers.
At that point, any number which contains another will appear in the list immediately after it.
123456
911
91125426
95225256

那么,它只是一个循环:

So then, it's just one loop:

if (thisString.StartsWith(previousString))
   {
   // It's a match.
   }


如果您能够假设所有紧急号码都是固定的位数,在大多数情况下; 3位数,那么问题更容易解决。如果是这样,那么它们可以被忽略。



否则你可以处理第二个唯一前缀号码列表:

代码之后:

If you are able to make an assumption that all emergency numbers will be a fixed number of digits, in most cases; 3 digits, then the problem is easier to solve. If so, then they can be ignored.

Otherwise you could process a second list of unique prefix numbers:
After your code:
while ((input = Console.ReadLine()) != null)
{
    phoneList.Add(input);
}







List<string> prefixes = new List<string>();
foreach(string number in phoneList)
{
    prefixes.Add(phoneList.SubString(0,2));
}</string></string>



然后检查该列表是否包含要验证的电话号码。


Then check that list contains the phone number being validated.