IOS去掉字符串中不相鄰的重復字符串

首先先聲明一下,這道題目的根本是根據(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:@""];

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容