My Swift Simple Solution


  • 1
    Y
    func firstUniqChar(_ s: String) -> Int {
            let stringArray = s.characters.map({ String($0) })
            var array:[String:Int] = [:]
            var ans:Int!
            
            for i in 0..<stringArray.count{
                //-1 means repeat
                array[stringArray[i]] = array[stringArray[i]] == nil ? i : -1 
            }
       
            for bas in array{
                if bas.value >= 0{
                    if ans == nil || bas.value < ans{
                        ans = bas.value    //get the smallest index
                    }
                }
            }
            return ans == nil ? -1 : ans
     }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.