2

更新:

正如@Blender 在 Python 中指出的那样set('aab').issubset(set('abb')) == True。对于我的情况,这需要返回 false。需要考虑每个字符的数量。


基本上我有两个字符串,我想确定一个是否是另一个的子集。例子:

String A: abcd
String B: dbace
String A is a subset of string B

字符可以按任何顺序排列,并且可以有重复的字符数。我曾尝试对字符串排序,然后使用 String.StartsWith,但这在某些情况下不起作用。例子:

String A: abcdd
string B: abbcdd
Ordering these and using StartsWith returns false because string B has two "b"s

我环顾四周,发现 Python 的 issubset 方法似乎可以满足我的要求,所以我很好奇是否有人在 .NET 中遇到过它的等价物(或有人自己提出的有效方法)。

注意:我正在寻找子集,而不是字谜。

4

2 回答 2

6

我所知道的没有任何内置的东西可以按照您的意愿行事。严格来说,这不是一个真正的子集,因为它应该像在 Python 中那样进行集合比较(集合中的每个项目都是唯一的),但它应该很容易制作。

public static bool IsSubsetOf<TSource>(this IEnumerable<TSource> lhs, IEnumerable<TSource> rhs)
{
    // O(m+n)
    var contents = rhs.ToList();
    foreach (var item in lhs)
    {
        if (!contents.Remove(item))
            return false;
    }
    return true;
}
"aab".IsSubsetOf("abb");      // false
"foo".IsSubsetOf("food");     // true
"foo".IsSubsetOf("goof");     // true
"bar".IsSubsetOf("barf");     // true
"abcd".IsSubsetOf("dbace");   // true
"abcdd".IsSubsetOf("abbcdd"); // true

如果你想要真正的系列机制,那也很简单。

public static bool IsTrueSubsetOf<TSource>(this IEnumerable<TSource> lhs, IEnumerable<TSource> rhs)
{
    return new HashSet<TSource>(lhs).IsSubsetOf(rhs);
}
于 2012-05-19T05:21:45.340 回答
-1

我认为最好的解决方案是对它们进行排序并按Contains方法检查子集。

new String(A.OrderBy(o=> o)).Contains(new String(B.OrderBy(o=>o)))

更新:

new String(A.OrderBy(o=> o)
            .Distinct())
     .Contains(new String(B.OrderBy(o=>o)
                           .Distinct()))
于 2012-05-19T05:24:14.907 回答