LeetCode in Kotlin

387. First Unique Character in a String

Easy

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:

Input: s = “leetcode”

Output: 0

Example 2:

Input: s = “loveleetcode”

Output: 2

Example 3:

Input: s = “aabb”

Output: -1

Constraints:

Solution

class Solution {
    fun firstUniqChar(s: String): Int {
        var ans = Int.MAX_VALUE
        var i = 'a'
        while (i <= 'z') {
            val ind = s.indexOf(i)
            if (ind != -1 && ind == s.lastIndexOf(i)) {
                ans = Math.min(ans, ind)
            }
            i++
        }
        return if (ans == Int.MAX_VALUE) {
            -1
        } else {
            ans
        }
    }
}