觀前提醒:
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
Note: You may assume the string contains only lowercase English letters.
直接破題:這題是找到字符串第 1 次出現長度為 1 的字串,且給定的字串都是英文小寫。
所以一開始我們可以利用 Dynamic Programing 的概念,採取以下步驟解題:
/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function (s) {
  //創造一個空的 map
  let frequencies = new Map();
  // 把 result 的預設值設定為 -1(題目要求)
  let result = -1;
  // 歷遍字串中每個字元,並記錄其出現次數。
  for (let char of s) {
    if (frequencies[char] === undefined) {
      frequencies[char] = 1;
    } else {
      frequencies[char]++;
    }
  }
  // 搜尋 map 中,第一次出現次數為 1 的字元,並回傳其位置。
  for (let i = 0; i < s.length; i++) {
    let char = s.charAt(i);
    if (frequencies[char] === 1) {
      return i;
    }
  }
  return result;
};
這題需要掌握住的內建物件 & 語法如下:
看完註解 + 上述相關資料後,這題應該就會變得不太困難才對~
謝謝大家的收看,LeetCode 小學堂我們下次見~