leetcode-字符串中的第一個唯一字符

給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。如果不存在,則返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.
 

注意事項:您可以假定該字符串只包含小寫字母。

代碼

/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function(s) {
    let a = {};
    for(let i=0;i<s.length;i++){
        if(!a[s[i]]){
            a[s[i]] = {index:i,count:1}
        }else{
            a[s[i]].index = i;
            a[s[i]].count++;
        }
    }
    let result = -1;
    for(let key in a){
        if(a[key].count === 1){
            result =  a[key].index
            return result
        }
    }
    return result
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章