根据我们用来检查的条件,该算法或代码应适用于字符串中任意数量的唯一字符。
例如(如果我有一个字符串,我想知道我们是否至少可以有7个唯一字符):
let number_of_distinct = Set(some_string.characters).count
if(number_of_distinct >= 7)
{
// yes we have at least 7 unique chars.
}
else
{
// no we don't have at least 7 unique chars.
}
但是,由于在Swift 4.0 +中更新字符串的方式,该技术在Swift 4.2 +中似乎已被弃用。
上面提到的这项技术的新正确方法是什么?
答案 0 :(得分:3)
只需删除.characters
let number_of_distinct = Set(some_string).count
if(number_of_distinct >= 7)
{
print("yes")
// yes we have at least 7 unique chars.
}
else
{
print("no")
// no we don't have at least 7 unique chars.
}
答案 1 :(得分:0)
您也可以在不使用Set的情况下执行此操作。
func printUniqueCompleteSubString(from string: String) {
var uniquString = ""
uniquString = string.reduce(uniquString) { (result, char) -> String in
if result.contains(char) {
return result
}
else {
return result + String.init(char)
}
}
print("Unique String is:", uniquString)
}