首先先声明一下,这道题目的根本是根据网上出现的一道面试题来做的,题目如下:“假设有一个字符串aabcad,请写一段程序,去掉字符串中不相邻的重复字符串,即上述字符串处理之后的输出结果为:aabcd”。根据题目,我不考虑出现类似aabcacd的这种下去掉a后c就不去掉的情况,如果出现这种情况,这直接把第二个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:@""];