HàPhan 河

May Leetcode Challenge - Day 5

Problem

First Unique Character in a String

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

Solution

Count appearance of each character and save in hash table
One more loop to find first count = 1

class Solution {
    func firstUniqChar(_ s: String) -> Int {
        var arr = Array(s)
        var search = [Character: Int]()
        
        for c in arr {
            search[c] = (search[c] ?? 0) + 1
        }
        
        for i in 0..<arr.count {
            if search[arr[i]] == 1 {
                return i
            }
        }
        
        return -1
    }
}

With the constraint lowercase letters, we can optimize by using an array instead of hashtable. The array length is equal two 26.

Comments