//这是最新的关于字符串中的第一个唯一字符的解法:
//给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
func firstUniqChar(_ s: String) -> Int {
for item in s {
if let index = s.firstIndex(of: item) {
if index == s.lastIndex(of: item) {
return index.encodedOffset
}
}
}
return -1
}
//通过索引找到它
func firstStr(_ s:String) -> Any{
var arr:[Any] = []
for scalar in s.unicodeScalars {
arr.append(scalar)
}
return arr[firstUniqChar(s)]
}
let str = "abaccddeeef"
print("第一个唯一字符索引:\(firstUniqChar(str))\n第一个唯一字符:\(firstStr(str))")
网友评论