字符串中的第一個惟一字符
給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。若是不存在,則返回 -1。數組
案例:code
s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.
注意事項:您能夠假定該字符串只包含小寫字母。索引
用count數組記錄每一個字符出現次數。ip
/** * @param {string} s * @return {number} */ var firstUniqChar = function(s) { let index = 0; let count = []; for(let i = 0; i < s.length; i++){ count[i] = 1; } for(let i = 0; i < s.length; i++){ if(count[i] == 1){ for(let j = i + 1; j < s.length; j++){ if(s[i] == s[j]){ count[i]++; count[j]++; } } } if(count[i] == 1){ return i; } } return -1; };