Compare corresponding character runs and require each typed run to be at least as long as the matching name run.
Complexity
O(n + m) time and O(1) space.
Check whether a typed string could result from long-pressing characters of a name.
Compare corresponding character runs and require each typed run to be at least as long as the matching name run.
O(n + m) time and O(1) space.
package main
func isLongPressedName(name string, typed string) bool {
i, j := 0, 0
for i < len(name) && j < len(typed) {
if name[i] != typed[j] {
return false
}
character := name[i]
nameCount, typedCount := 0, 0
for i < len(name) && name[i] == character {
i++
nameCount++
}
for j < len(typed) && typed[j] == character {
j++
typedCount++
}
if typedCount < nameCount {
return false
}
}
return i == len(name) && j == len(typed)
}
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
i = j = 0
while i < len(name) and j < len(typed):
if name[i] != typed[j]: return False
character = name[i]
name_count = typed_count = 0
while i < len(name) and name[i] == character: i, name_count = i + 1, name_count + 1
while j < len(typed) and typed[j] == character: j, typed_count = j + 1, typed_count + 1
if typed_count < name_count: return False
return i == len(name) and j == len(typed)
function isLongPressedName(name: string, typed: string): boolean {
let i = 0;
let j = 0;
while (i < name.length && j < typed.length) {
if (name[i] !== typed[j]) return false;
const character = name[i]; let nameCount = 0; let typedCount = 0;
while (i < name.length && name[i] === character) { i += 1; nameCount += 1; }
while (j < typed.length && typed[j] === character) { j += 1; typedCount += 1; }
if (typedCount < nameCount) return false;
}
return i === name.length && j === typed.length;
}