
Objective-C实现字符串排列算法(附完整源码)
发布日期:2025-04-25 19:54:17
浏览次数:5
分类:精选文章
本文共 1432 字,大约阅读时间需要 4 分钟。
Objective-C实现字符串排列算法
下面是一个用Objective-C实现的字符串排列算法的完整源码。这个程序会生成给定字符串的所有排列,并将结果打印出来。
#import
@interface StringPermutations : NSObject - (void)permuteString:(NSString *)inputString; @end #import "StringPermutations.h" @implementation StringPermutations - (void)permuteString:(NSString *)inputString { NSString *chars = inputString; NSArray *charArray = [chars componentsSeparatedByString: @""]; if (charArray.count <= 1) { NSLog(@"排列结果:%@", inputString); return; } NSMutableString *result = [NSMutableString string]; void permute(NSArray *array, NSUInteger index, NSString *currentString, NSMutableArray *used, NSString *resultString) { if (index == array.count) { [resultString appendFormat: @"'%@'", currentString]; [result appendString: resultString]; [resultString reset]; return; } for (NSUInteger i = 0; i < array.count; i++) { if (![(NSNumber *)[array objectAtIndex:i] boolValue]) { [permute array: array, index: i+1, currentString: [currentString appendFormat: @"'%c'", [array[i] characterAtIndex: 0]], used: used, resultString: resultString); } } [resultString reset]; } NSMutableArray *used = [NSMutableArray array]; [permute charArray, 0, @"", used, result]; for (NSString *str in [result componentsSeparatedByString: @"\n"]) { NSLog(@"排列结果:%@", str); } } @end
发表评论
最新留言
网站不错 人气很旺了 加油
[***.192.178.218]2025年03月30日 16时29分53秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!