计算给定字符串的所有可能的子字符串
如何计算 a 的所有可能的子字符串细绳?例如给定一个字符串 ABCDE。它所有可能的子串都是
A, 乙, C、 D、 乙, AB, 公元前, 光盘, 德, ABC, 二进制码, CDE, ABCD, BCDE, ABCDE
谢谢!伪代码将受到高度赞赏。 :D
Possible Duplicate:
How to find all substrings of a string in PHP
Find all subsets of a list
How can I compute all the possible substrings of a string? For example given a string ABCDE. All its possible substrings will be
A,
B,
C,
D,
E,
AB,
BC,
CD,
DE,
ABC,
BCD,
CDE,
ABCD,
BCDE,
ABCDE
Thanks! A pseudocode will be highly appreciated. :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用两个 for 循环:
您也可以使用两个 for 循环这样做:
您可能还希望在返回的序列中包含空字符串
""
,因为它是一个子字符串所有字符串。您还需要考虑多次生成重复字符串是否有效(例如,您是否将“ABA”作为“ABABA”的子字符串返回两次?)。如果答案是否定的,只需创建一个名为
alreadyYielded
的哈希表,每当您生成时,如果您已经生成了字符串,则中止,否则将值添加到哈希表中,以防您再次看到它。例如:Just use two for-loops:
You can also do it this way with two for-loops:
You probably want to include the empty string
""
in the sequence you return as well, as it is a substring of all strings.You also need to consider if it is valid to yield a duplicate string multiple times (e.g. do you return "ABA" twice as a substring of "ABABA"?). If the answer is no, merely make a hashtable called
alreadyYielded
, and whenever you yield, abort if you've already yielded the string, otherwise add the value to the hashtable in case you see it again. For example:这是一个 2 美分的答案:
要获得组合的数量,只需在内循环中添加一个计数器即可。
例如,在 Perl 中,这可能看起来像:
Here's a 2-cent answer:
To get the number of combinations, simply add a counter to the inner loop.
For instance, in perl, this might look like: