首先先聲明一下,這道題目的根本是根據(jù)網(wǎng)上出現(xiàn)的一道面試題來做的,題目如下:“假設有一個字符串a(chǎn)abcad,請寫一段程序,去掉字符串中不相鄰的重復字符串,即上述字符串處理之后的輸出結果為:aabcd”。根據(jù)題目,我不考慮出現(xiàn)類似aabcacd的這種下去掉a后c就不去掉的情況,如果出現(xiàn)這種情況,這直接把第二個c也去掉,結果就是aabcd。
直接上代碼:
NSString *a = @"aabcad";
? ? NSMutableArray *temps = [NSMutableArray array];
? ? NSString*temp =nil;
? ? for(inti =0; i < [a length]; i++)// 遍歷每個字符
? ? {
?? ? ? temp = [a substringWithRange:NSMakeRange(i,1)];
?? ? ? [temps addObject:temp];
? ? }
? ? NSMutableArray *indexs = [NSMutableArray array];
? ? NSString*t =nil;
? ? NSString*t1 =nil;
? ? for(inti =0; i < temps.count; i ++) {
? ? ? ? t = temps[i];
? ? ? ? for(intj =0; j < i; j++) {
? ? ? ? ? ? t1 = temps[j];
? ? ? ? ? ? //判斷兩個字符是否相等,切不相鄰
? ? ? ? ? ? if(t == t1 && i != j +1) {
? ? ? ? ? ? ? ? [indexs addObject:[NSStringstringWithFormat:@"%d",i]];
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? //去重
? ? NSSet*set = [NSSetsetWithArray:indexs];
? ? //獲取不相鄰重復字符的位置
? ? for(NSString *tem in set) {
? ? ? ? NSIntegeridx = [temintegerValue];
? ? ? ? [temps replaceObjectAtIndex:idx withObject:@" "];
? ? }
? ? NSString *ttt = [temps componentsJoinedByString:@" "];
//獲得最后字符串(aabcd)
? ? NSString *tttt = [ttt stringByReplacingOccurrencesOfString:@" " withString:@""];