在List<string>中计算相邻相似项数

4
我正在尝试查找列表中相似的相邻项并计算其数量,例如:

List<string> list = new List<string> {"a", "a", "b", "d", "c", "c"};

期望输出:

a = 2,c = 2

我所做的是使用for循环遍历列表的每个元素,以查看它是否具有类似的相邻元素,但可以理解地产生了ArgumentOutOfRangeException(),因为我不知道如何跟踪迭代器的位置,以使其不超出边界。这是我所做的:

for (int j = 0; j < list.Count; j++)
{
      if (list[j] == "b")
      {
             if ((list[j + 1] == "b") && (list[j - 1] == "b"))
             {
                     adjacent_found = true;
             }
      }
}

话虽如此,如果有比使用for循环更简单的方法来查找列表中类似相邻的元素,请指教。谢谢。


请定义“相似”;你是不是真的指的是“相等”? - Thomas Levesque
7
对于 { "a", "a", "b", "a", "a", "a" },期望的输出是什么? - tia
你的代码示例与你描述的示例列表不符合预期。 - BrokenGlass
5个回答

3
您可以这样做:
static IEnumerable<Tuple<string, int>> FindAdjacentItems(IEnumerable<string> list)
{
    string previous = null;
    int count = 0;
    foreach (string item in list)
    {
        if (previous == item)
        {
            count++;
        }
        else
        {
            if (count > 1)
            {
                yield return Tuple.Create(previous, count);
            }
            count = 1;
        }
        previous = item;
    }

    if (count > 1)
    {
        yield return Tuple.Create(previous, count);
    }
}

0

维护一个大小为256的int数组,初始化为1。运行一个循环[O(n)],从i=0到i-2,将每个字符与下一个字符进行比较。如果相同,则找出字符的ascii值,并增加数组中相应的值。 希望这可以帮助你!


0
for (int i= 0; i < list.Count; i++)
   {
      for (int j = i + 1; j < list.Count; j++)
        {
           if (list[i] == list[j])
             {
                adjacent_found = true;
                count++;
             }
        }
   }

这也会找到非相邻的项,而且效率非常低(当它可以是O(n)时,它是O(n²))。 - Thomas Levesque

0

请检查:

Dictionary<char,int> dic=new Dictionary<char,int>();
for(int i=1;i<list.count;i++)
{
          if(list[i]==list[i-1])
                {
                      if(dic.ContainsKey(list[i]))
                                 {
                                   dic[list[i]]+=1;
                             }
                          else
                                 { 
                                    dic.Add(list[i],2)
                                  }
                  }
}

0
为避免“ArgumentOutOfRangeException”错误,请使用“for (int j = 1; j < list.Count - 1; j++)”。但是,这种方法无法实现所需的答案。请尝试以下方法:
IEnumerable<Adjacent> CountAdjacents(List<string> source)
{
    var result = new List<Adjacent>();

    for (var i = 0; i < source.Count() - 1; i++)
    {
        if (source[i] == source[i + 1])
        {
            if (result.Any(x => x.Word == source[i]))
            {
                result.Single(x => x.Word == source[i]).Quantity++;
            }
            else
                result.Add(new Adjacent
                {
                    Word = source[i],
                    Quantity = 2
                });
        }
    }
    return result;
}

class Adjacent
{
    public string Word;
    public int Quantity;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接