计算List 中相似的相邻项

我正在尝试在List中找到类似的相邻项目并计算其编号,例如:

List list = new List {"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循环迭代之外,还有另一种更简单的方法可以在List中找到相似的相邻元素,请提供建议。 谢谢。

你可以这样做:

 static IEnumerable> FindAdjacentItems(IEnumerable 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); } } 
 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++; } } } 

检查一下:

 Dictionary dic=new Dictionary(); for(int i=1;i 

为了避免使用ArgumentOutOfRangeException for (int j = 1; j < list.Count - 1; j++) 。 这种方式无法实现所需的答案。 试试这个:

 IEnumerable CountAdjacents(List source) { var result = new List(); 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; } 

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