java 字符串所有子串,如何获取一个字符串的所有子组合(Java或C ++等)

Let's say I've a string "12345" I should obtain all subsequence combinations of this string such as:

--> 1 2 3 4 5

--> 12 13 14 15 23 24 25 34 35 45

--> 123 124 125 234 235 345

--> 1234 1235 1245 1345 2345

--> 12345

Please note that I grouped them in different number of chars but not changed their order. I need a method/function does that.

解决方案

You want a powerset. Here are all the questions on StackOverflow that mention powersets or power sets.

Here is a basic implementation in python:

def powerset(s):

n = len(s)

masks = [1<

for i in xrange(2**n):

yield [s[j] for j in range(n) if (masks[j] & i)]

if __name__ == '__main__':

for elem in powerset([1,2,3,4,5]):

print elem

And here is its output:

[]

[1]

[2]

[1, 2]

[3]

[1, 3]

[2, 3]

[1, 2, 3]

[4]

[1, 4]

[2, 4]

[1, 2, 4]

[3, 4]

[1, 3, 4]

[2, 3, 4]

[1, 2, 3, 4]

[5]

[1, 5]

[2, 5]

[1, 2, 5]

[3, 5]

[1, 3, 5]

[2, 3, 5]

[1, 2, 3, 5]

[4, 5]

[1, 4, 5]

[2, 4, 5]

[1, 2, 4, 5]

[3, 4, 5]

[1, 3, 4, 5]

[2, 3, 4, 5]

[1, 2, 3, 4, 5]

Notice that its first result is the empty set. Change the iteration from this for i in xrange(2**n): to this for i in xrange(1, 2**n): if you want to skip an empty set.

Here is the code adapted to produce string output:

def powerset(s):

n = len(s)

masks = [1<

for i in xrange(2**n):

yield "".join([str(s[j]) for j in range(n) if (masks[j] & i)])

Edit 2009-10-24

Okay, I see you are partial to an implementation in Java. I don't know Java, so I'll meet you halfway and give you code in C#:

static public IEnumerable> powerset(IList s)

{

int n = s.Count;

int[] masks = new int[n];

for (int i = 0; i < n; i++)

masks[i] = (1 << i);

for (int i = 0; i < (1 << n); i++)

{

List newList = new List(n);

for (int j = 0; j < n; j++)

if ((masks[j] & i) != 0)

newList.Add(s[j]);

yield return newList;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值