Question:

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

Example:

  1. s = "leetcode"
  2. return 0.
  3. s = "loveleetcode",
  4. return 2.

Solution:

  1. /**
  2. * @param {string} s
  3. * @return {number}
  4. */
  5. var firstUniqChar = function(s) {
  6. for (let i in s) {
  7. if (s.indexOf(s[i]) === s.lastIndexOf(s[i])){
  8. return i;
  9. }
  10. }
  11. return -1;
  12. };

Runtime: 228 ms, faster than 6.39% of JavaScript online submissions for First Unique Character in a String.

  1. /**
  2. * @param {string} s
  3. * @return {number}
  4. */
  5. var firstUniqChar = function(s) {
  6. const obj = {}
  7. for (let i in s) {
  8. if(!obj[s[i]]) obj[s[i]] = 0;
  9. obj[s[i]]++;
  10. }
  11. for (let j in s) {
  12. if(obj[s[j]] === 1) {
  13. return j;
  14. }
  15. }
  16. return -1;
  17. };

Runtime: 252 ms, faster than 5.51% of JavaScript online submissions for First Unique Character in a String