Skip to content

Instantly share code, notes, and snippets.

@ajayjapan
Last active October 3, 2016 01:55
Show Gist options
  • Save ajayjapan/18cc21599a4048569b1ff941422b76f1 to your computer and use it in GitHub Desktop.
Save ajayjapan/18cc21599a4048569b1ff941422b76f1 to your computer and use it in GitHub Desktop.
Given a string return all the permutations of that string.
-(NSArray<NSString> *)permutationsOfString:(NSString *)s {
NSMutableArray<NSString> *res = [NSMutableArray array];
if (s.length == 1) {
[res addObject:s];
} else if (s.length > 1) {
int lastIndex = s.length - 1;
String last = s.substring(lastIndex);
String rest = s.substring(0, lastIndex);
res = merge(permutation(rest), last);
}
return res;
}
-(NSArray<NSString> *)mergeArray:(NSArray<String> *)list withString:(NSString *)c {
NSMutableArray<NSString> *res = [NSMutableArray array];
for (NSString *s in list) {
for (int i = 0; i <= s.length; ++i) {
NSMutableString *ps = [NSMutableString stringFromString:s]
[s insertString:c atIndex:i];
[res addObject:ps];
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment