iOS面试常见的算法题、自己面试遇到的、希望能帮到大家、有错误欢迎指正
删除给定字符串中重复连续的字符。如“aaabccdeeeeeghkccc” ->“abcdeghkc”
一、OC方法
- (NSString *)removeDuplicate:(NSString *)input {
NSMutableString *string = [NSMutableString stringWithFormat:@"%@", input];
for (int i = 0; i < string.length - 1; i++) {
for (int j = i+1 ; j < string.length; j++) {
NSString *str1 = [string substringWithRange:NSMakeRange(i, 1)];
NSString *str2 = [string substringWithRange:NSMakeRange(j, 1)];
if ([str1 isEqualToString:str2]) {
[string deleteCharactersInRange:NSMakeRange(j, 1)];
j--;
} else {
break;
}
}
}
NSLog(@"删除后得到字符串===============%@",string);
return string;
}
二、swift方法
func removeDuplicate( input :String) -> String {
var strResult:String = ""
//字符串转数组
var array = input.map { String($0) }
for i in 0..<array.count {
var j = i + 1
while j < array.count{
let str1 = array[i]
let str2 = array[j]
if str1 == str2 {
array.remove(at: j)
j = j-1
}else{
break
}
j = j + 1
}
}
//数组转字符串
strResult = array.joined()
print("删除后得到字符串===============\(strResult)")
return strResult
}
网友评论