First Unique Character in a String
題目
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.思路
程式碼
class Solution {
func firstUniqChar(_ s: String) -> Int {
var chars = Array(s)
// 注意Dictionary的宣告寫法
var dic = Dictionary<Character, Int>()
for index in 0..<chars.count {
let key = chars[index]
// 記錄每個char出現的次數
if dic[key] != nil {
dic[key]! += 1
} else {
dic[key] = 1
}
}
var hasMinIndex = false
var minIndex = Int.max
for key in dic.keys {
// 只找出現次數為1
if dic[key]! == 1 {
hasMinIndex = true
// 如何利用字元回找array的index
let index = chars.firstIndex(of: key)
minIndex = min(minIndex, index!)
}
}
if hasMinIndex {
return minIndex
} else {
return -1
}
}
}複雜度
Last updated