|
| 1 | +/** |
| 2 | + 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. |
| 3 | + |
| 4 | + 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. |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | + Example 1: |
| 9 | + Input: name = "alex", typed = "aaleex" |
| 10 | + Output: true |
| 11 | + Explanation: 'a' and 'e' in 'alex' were long pressed. |
| 12 | + |
| 13 | + Example 2: |
| 14 | + Input: name = "saeed", typed = "ssaaedd" |
| 15 | + Output: false |
| 16 | + Explanation: 'e' must have been pressed twice, but it was not in the typed output. |
| 17 | + |
| 18 | + |
| 19 | + Constraints: |
| 20 | + - 1 <= name.length, typed.length <= 1000 |
| 21 | + - name and typed consist of only lowercase English letters. |
| 22 | + */ |
| 23 | +class Solution { |
| 24 | + func isLongPressedName(_ name: String, _ typed: String) -> Bool { |
| 25 | + var nameArr = [String(name.first!)] |
| 26 | + for (i, c) in name.enumerated() { |
| 27 | + if i > 0 { |
| 28 | + var character = nameArr.last!.last |
| 29 | + if character == c { |
| 30 | + var last = nameArr.popLast()! |
| 31 | + last.append(c) |
| 32 | + nameArr.append(last) |
| 33 | + } else { |
| 34 | + nameArr.append(String(c)) |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + var typedArr = [String(typed.first!)] |
| 40 | + for (i, c) in typed.enumerated() { |
| 41 | + if i > 0 { |
| 42 | + var character = typedArr.last!.last |
| 43 | + if character == c { |
| 44 | + var last = typedArr.popLast()! |
| 45 | + last.append(c) |
| 46 | + typedArr.append(last) |
| 47 | + } else { |
| 48 | + typedArr.append(String(c)) |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + if nameArr.count != typedArr.count { |
| 54 | + return false |
| 55 | + } |
| 56 | + for (i, e) in nameArr.enumerated() { |
| 57 | + let element = typedArr[i] |
| 58 | + if e.first != element.first { |
| 59 | + return false |
| 60 | + } else { |
| 61 | + if e.count > element.count { |
| 62 | + return false |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + return true |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +let s = Solution() |
| 71 | +let r = s.isLongPressedName("leelee", "lleeelee") |
| 72 | +print(r) |
0 commit comments