朋友给我发了这个题目, 一看这种问题肯定属于网红题, 肯定网上有很多解答, 有了思路后就想网搜一下看看大家有没有其它想法, 结果翻了一圈下来, 看到的解答都是不正确的, 就自己写了些代码放上来, 仅供参考:
注: 不仅仅是要aabcad->aabcd这种结果, 所求是移除所有有重复但不相邻的, 如无相邻的则不管, 如abab->abab
/*
aabcad -> aabcd, abbdcaabd -> bbdcaad ...
思路:
1. 获取每个字符出现的次数;
2. 定位个数为2以上的每个字母的位置
3. 记录要删除字符的位置
4. 对应删除
*/
- (NSString *)removeTheEqualButNotNearbyCharForStr:(NSString *)fromStr {
if (fromStr.length <= 3) return fromStr;
// 统计每个字符出现的次数
NSMutableDictionary *chatCountDict = [[NSMutableDictionary alloc] init];
int count = 0; BOOL equal = NO;
for (int i = 0; i < fromStr.length; i++) {
count = 0; equal = NO;
for (int j = 0; j < i; j++) {
if ([fromStr characterAtIndex:i] == [fromStr characterAtIndex:j]) {
equal = YES;
break;
}
}
if (equal) continue;
for (int j = i; j < fromStr.length; j++) {
if ([fromStr characterAtIndex:i] == [fromStr characterAtIndex:j]) count++;
}
[chatCountDict setValue:@(count) forKey:[fromStr substringWithRange:NSMakeRange(i, 1)]];
}
// 保留2个以上的字符记录
[chatCountDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if ([obj intValue] <= 2) [chatCountDict removeObjectForKey:key];
}];
// 获取字符对应位置
NSMutableDictionary *chatLocationDict = [[NSMutableDictionary alloc] init];
[chatCountDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL * _Nonnull stop) {
NSMutableArray *locationArr = [[NSMutableArray alloc] init];
for (int i = 0; i < fromStr.length; i++) {
if ([[NSString stringWithFormat:@"%c",[fromStr characterAtIndex:i]] isEqualToString:key]) [locationArr addObject:@(i)];
}
[chatLocationDict setValue:locationArr forKey:key];
}];
// 记录要删除字符的位置
NSMutableArray *indexArrM = [[NSMutableArray alloc] init];
for (int j = 0; j < chatLocationDict.allKeys.count; j++) {
NSArray *locaArr = chatLocationDict[chatLocationDict.allKeys[j]];
BOOL hasEqualNearBy = NO;
for (int i = 0; i < locaArr.count - 1; i++) {
if ([locaArr[i] intValue] + 1 == [locaArr[i + 1] intValue]) hasEqualNearBy = YES;
}
if (!hasEqualNearBy) continue;
for (int i = 0; i < locaArr.count; i++) {
if (
(i == 0 && ([locaArr[i] intValue] + 1 != [locaArr[i + 1] intValue])) ||
(i == locaArr.count -1 && ([locaArr[i - 1] intValue] + 1 != [locaArr[i] intValue])) ||
(i != 0 && i != locaArr.count - 1 && (([locaArr[i] intValue] + 1 != [locaArr[i + 1] intValue]) && ([locaArr[i - 1] intValue] + 1 != [locaArr[i] intValue])))
) {
[indexArrM addObject:locaArr[i]];
}
}
}
// 移除
NSMutableArray *arrM = [[NSMutableArray alloc] initWithCapacity:fromStr.length];
for (int i = 0; i < fromStr.length; i++) [arrM addObject:[NSString stringWithFormat:@"%c",[fromStr characterAtIndex:i]]];
NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
for (NSNumber *num in indexArrM) [indexSet addIndex:[num integerValue]];
[arrM removeObjectsAtIndexes:indexSet];
NSMutableString *strM = [[NSMutableString alloc] init];
for (NSString *str in arrM) [strM appendString:str];
return strM.copy;
}