Last active
October 3, 2016 01:55
-
-
Save ajayjapan/18cc21599a4048569b1ff941422b76f1 to your computer and use it in GitHub Desktop.
Given a string return all the permutations of that string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(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