我正在尝试编写一个方法来生成具有固定长度的给定NSString的所有子串,但是我遇到了困难。这就是我想要的想法:
-(int)countGoodSubstringsOfString:(NSString*)str ofLength:(int)len {
int cnt = 0;
for (NSString *substr substring of str of length len) {
if ([self isGoodSubstring:substr ofString:str])
cnt++;
}
return cnt;
}
子字符串是指len
中str
个字符的所有可能组合。如果str = @"ABCDE"
和len = 4
,那么我需要获得5个子字符串:@"ABCD", @"ABCE", @"ABDE", @"ACDE", @"BCDE"
。
如果修复了len
,那么我可以编写嵌套的for
循环来获取所有这样的子串
NSString *substr = @"";
for (int i=0; i<str.length-len+1; ++i) {
substr = [substr stringByAppendingString:[str substringWithRange:NSMakeRange(i,1)]];
for (int j=i+1; j<str.length-len+2; ++j) {
substr = [substr stringByAppendingString:[str substringWithRange:NSMakeRange(j,1)]];
...
for(int k=j+1; k<str.length; ++k) {
substr = [substr stringByAppendingString:[str substringWithRange:NSMakeRange(k,1)]];
if ([self isGoodSubstring:substr ofString:str])
cnt++;
但由于len
是输入的一部分,我无法提前知道。我怎样才能解决这个问题呢?
答案 0 :(得分:1)
不完全清楚你想要做什么,但如果你想让所有字符串的子串由给定长度的@“”分隔 - 那么它看起来像这样:
NSString *str = @"length string blah lskdnflskdls lkjbfe lkfngj";
int length = 6;
NSPredicate *filter = [NSPredicate predicateWithFormat:@"SELF.length = %d", length];
NSArray *arr = [[str componentsSeparatedByString:@" "] filteredArrayUsingPredicate:filter];
NSLog(@"filtered substrings: %@", arr);
输出如下:
filtered substrings: (
length,
string,
lkjbfe,
lkfngj
)
答案 1 :(得分:0)
编辑:我终于找到了解决方案。它使用与您相同的想法,但它是递归的,因此您不必知道长度。
-(int)countGoodSubstringsOfString:(NSString*)str ofLength:(int)len recStr:(NSString *)recStr from:(int)from{
/// C(str.length, str.length-len)
if (!recStr) {
recStr = @"";
}
if ([recStr length]==len) {
if ([self isGoodSubstring:substr ofString:str])
return 1;
return 0;
}
int cnt = 0;
for (int i=from; i<=str.length-len+[recStr length]; i++) {
NSString *substr = [recStr stringByAppendingString:[str substringWithRange:NSMakeRange(i, 1)]];
cnt += [self countGoodSubstringsOfString:str ofLength:len recStr:substr from:i+1];
}
return cnt;
}
初始通话应该如下所示:
int cnt = [self countGoodSubstringsOfString:@"ABCDEF" ofLength:4 recStr:nil from:0];