查找字符串行中出现的第一个最长字符

本文关键字:第一个 字符 字符串 查找 | 更新日期: 2023-09-27 18:05:42

    int lines = File.ReadAllLines(Path).Length; // count lines index
    public string input = "";
    public string mtd() // This method should return the first long occurrence index (ry) and the longest occurrence of the char (rx)
    {
        Dictionary<char, int> dict = new Dictionary<char, int>();
        int max = 0;
        foreach (char c in input)
        {
            int i;
            dict.TryGetValue(c, out i);
            i++;
            if (i > max)
            {
                max = i;
            }
            dict[c] = i;
        }
        string rx = "";
        string ry = "";
        foreach (KeyValuePair<char, int> chars in dict)
        {
            string x = chars.Key.ToString();
            string y = chars.Value.ToString();
            if (chars.Value == max)
            {
                rx = x;
                ry = y;
            }
        }
        return rx;
       }

我的目标是:

取一个带有OpenFileDialog按钮的file.txt(有更多文本行)在richTextBox中显示第一个最长子字符串(字符出现)和每行第一个最长字符出现的索引(从零开始)。

这是我的意思的一个例子。

在文本文件中,我有3行,它们是:

aaabb

ccddddd

efffggggg

结果应该是:

aaa, 0

ddddd 1

ggggg 4我看过关于这个问题的其他问题,但我没有找到解决方案。任何想法?

查找字符串行中出现的第一个最长字符

因此,这是一种与其他方法略有不同的方法,但您可以尝试使用正则表达式。以下表达式将匹配重复字符的模式:

(.)('1+)

(.)匹配除换行符以外的任何字符,('1+)匹配前一个匹配的1次或多次重复。

如果需要,您可以使用(.)以外的其他内容作为第一个匹配组。这取决于你关心的是什么类型的重复。例如,如果您只关心重复的"a",则可以使用(a)代替。

这种方法为您提供了很大的灵活性,因为(.)组可以由字符串变量定义,而不是硬编码。

算法:

  1. 您将每次从文件中提取一行。
  2. 然后使用此正则表达式搜索该行上的匹配项。
  3. 每次找到匹配项时,将其与其偏移量一起存储。
  4. 当你完成一行后,从数组中选择最长的字符串。
  5. 将其信息打印到您的结果字符串中。
  6. 继续输入下一行。

有一个用于正则表达式的c#系统汇编。

https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex (v = vs.110) . aspx

你可以这样做:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main()
        {
            //var lines = File.ReadAllLines("C:''text.txt");
            var lines = new List<string> { "aaabb", "ccddddd", "efffggggg" };
            var result = (
                from line in lines
                let matches = Regex.Matches(line, "(.)''1+").Cast<Match>()
                let maxLen = matches.Max(match => match.Length)
                let maxMatch = matches.First(match => match.Length == maxLen)
                let index = line.IndexOf(maxMatch.Value)
                select string.Format("{0},{1}", maxMatch.Value, index)
            ).ToList();
            result.ForEach(Console.WriteLine);
        }
    }
}

下面的程序将给出您所要求的结果,并在O(n)时间内运行。

var lines = new List<string> { "aaabb", "ccddddd", "efffggggg" };
foreach (var line in lines)
{
    if (string.IsNullOrEmpty(line)) // if the line is null or empty then skip it.
    {
        Console.WriteLine("Empty or Null string.");
        continue;
    }
    char prev = line[0]; // The previous character seen starts with the first character
    int maxSeen = 0; // The maximum number of consecutive chars seen
    int maxSeenIndex = -1; // The index of the maximum seen chars.
    int currentSeen = 1; // The current number of consecutive chars seen.
    int currentSeenIndex = 0; // The index of the current chars seen.
    for (int i = 1; i < line.Length; i++) // Start at 1 to skip the first character.
    {
        if (prev == line[i]) // If the current character is the same as the previous
        {
            currentSeen++; // increment the number of current chars seen.
        }
        else // If the current character is different
        {
            if (currentSeen > maxSeen) // Check if the current Seen is more than max
            {
                maxSeen = currentSeen;
                maxSeenIndex = currentSeenIndex;
            }
            currentSeen = 1; // reset the current seen to 1
            currentSeenIndex = i; // set the current seen index to the current index
        }
        prev = line[i]; // set the current char to the previous
    }
    if (currentSeen > maxSeen) // Have to do this check again 
    {
        maxSeen = currentSeen;
        maxSeenIndex = currentSeenIndex;
    }
    Console.WriteLine(line.Substring(maxSeenIndex, maxSeen) + ", " + maxSeenIndex);
}

下面是一个函数,对给定的行执行您想要的操作:

 public static string GetCharacterRepetitionAndPosition(string s)
    {
        if (string.IsNullOrWhiteSpace(s))
            return s;
        var result = (from ch in s
                      group ch by ch into g
                      select new { Cnt = g.Count(), Ch = g.Key });
        var maxCnt = -1;
        char theMaxChar =char.MinValue;
        int howManyCharacters;
        foreach (var item in result)
        {
            if (item.Cnt > maxCnt)
            {
                maxCnt = item.Cnt;
                theMaxChar = item.Ch;
                howManyCharacters = item.Cnt;
            }
        }

        var idx = s.IndexOf(theMaxChar);
        return new string(theMaxChar,maxCnt) + "," + idx;
    }

用法如下:

 using (var fileStream = new FileStream(Path, FileMode.Open, FileAccess.Read))
        {
            using (var streamReader = new StreamReader(fileStream))
            {
                var line = streamReader.ReadLine();
                var res = GetCharacterRepetitionAndPosition(line);
                // do whatever you want with this output
                Console.WriteLine(res);
            }
        }
算法复杂度分析:

1) select with groupby = 0 (N)

2)结果上的foreach也是O (N)

3) IndexOf()调用是0 (N)

所以总复杂度(大O)是O (N)

这里发生了什么:

1)我们首先把所有的角色按他们的幻影分组,我们也计算他们在一组中有多少人。

2)我们迭代这个结果,我们记住字符的最大字符数以及字符是什么

3)我们返回一个字符串(最高显形的字符)