Finding longest word in string

后端 未结 4 1323
醉梦人生
醉梦人生 2021-01-19 04:13

Ok, so I know that questions LIKE this have been asked a lot on here, but I can\'t seem to make solutions work. I am trying to take a string from a file and find the longest

4条回答
  •  别那么骄傲
    2021-01-19 04:55

    Don't split the string, use a Regex

    If you care about performance you don't want to split the string. The reason in order to do the split method will have to traverse the entire string, create new strings for the items it finds to split and put them into an array, computational cost of more than N, then doing an order by you do another (at least) O(nLog(n)) steps.

    You can use a Regex for this, which will be more efficient, because it will only iterate over the string once

    var regex = new Regex(@"(\w+)\s",RegexOptions.Compiled);
    var match = regex.Match(fileText);
    var currentLargestString = "";
    
    while(match.Success)
    {
         if(match.Groups[1].Value.Length>currentLargestString.Length)
         {
             currentLargestString = match.Groups[1].Value;
         }
    
         match = match.NextMatch();
    }
    

    The nice thing about this is that you don't need to break the string up all at once to do the analysis and if you need to load the file incrementally is a fairly easy change to just persist the word in an object and call it against multiple strings

    If you're set on using an Array don't order by just iterate over

    You don't need to do an order by your just looking for the largest item, computational complexity of order by is in most cases O(nLog(n)), iterating over the list has a complexity of O(n)

    var largest = "";
    foreach(var item in strArr)
    {
        if(item.Length>largest.Length)
            largest = item;
    }
    

提交回复
热议问题