Home > database >  Smallest Unique subsequence from list of string
Smallest Unique subsequence from list of string

Time:10-27

I want to get only the smallest unique subsequence from list of string. For example:

  1. [1,11,111,12,13] - I want to get only the first value i.e. 1
  2. [11,12,13,131,141,14,111] - I want values - 11,12,13,14 only.

I am trying but facing issue to get the exact value. Values is the collection of element.

var str = new List<string>();
string[] str1 = values.OrderBy(x => x.Length).ToArray();

foreach(var s in str1)
{
    if (str.count() < 1)
        str.Add(s);
    else
    {
        int count = str.Count;
        for (int i=0; i < count; i  )
        {
            if (s.StartsWith(str[i]))
            {
                break;
            }
            str.Add(s);
        }
    }
}

Any help would be appreciated. Thanks!

CodePudding user response:

You were almost there. But you were adding s before you checked all elements already contained in the set. And the check for "still empty result" isn't really needed.

If you can use Linq, the following should work. See code for explanaition

public static List<string> prefixFree(List<string> words) {
    //order the words by their length
    var w = words.OrderBy(x => x.Length);

    var result = new List<string>();

    //for each of the words check
    foreach (var s in w) {
        //if it starts with any of the words already in the result
        if (!result.Any(x => s.StartsWith((x))))
            //if no match is found, add it to the result
            result.Add(s);
    }
    
    return result;
}

CodePudding user response:

Try/improve as needed...

//ints
var ints = new List<int> { 1, 2, 3, 4, 7, 8, 7, 3, 9 };

//strings
var strs = new List<string> { "foo", "bar", "baz", "lorem", "1", "2", "baz", "7", "1", "8", "9", "1" };

//ints
GetUniques<int>(ints);

//strings
GetUniques<string>(strs);

void GetUniques<T>(IEnumerable<T> e)
{
    //if count > 1 then it has 1 or more duplicates...
    var group = e.GroupBy(g => g).Where(g => g.Count() == 1);
    foreach (var g in group)
    {
        Console.WriteLine(g.Key);
    }
}
  • Related