Question:

Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.

You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

Example:

  1. Input: name = "alex", typed = "aaleex"
  2. Output: true
  3. Explanation: 'a' and 'e' in 'alex' were long pressed.
  4. Input: name = "laiden", typed = "laiden"
  5. Output: true
  6. Explanation: It's not necessary to long press any character.
  1. Input: name = "saeed", typed = "ssaaedd"
  2. Output: false
  3. Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
  4. Input: name = "leelee", typed = "lleeelee"
  5. Output: true

Solution:

  1. /**
  2. * @param {string} name
  3. * @param {string} typed
  4. * @return {boolean}
  5. */
  6. var isLongPressedName = function(name, typed) {
  7. if (!name || !typed) return false;
  8. // 相同则无需判断
  9. if (name === typed) return true;
  10. let regStr = '';
  11. for (let i in name) {
  12. regStr += name[i] + '+';
  13. }
  14. const regx = new RegExp(regStr,'g');
  15. return regx.test(typed);
  16. };

Runtime: 80 ms, faster than 24.19% of JavaScript online submissions for Long Pressed Name.