get index out of range error
def validWordAbbreviation(word: str, abbr: str) -> bool:
"""
Check if abbreviation is valid for the given word.
Time Complexity: O(n) where n is the length of abbr
Space Complexity: O(1)
"""
i,j=0,0
while i<len(word) and j<len(abbr):
number=""
while abbr[j].isdigit():
number+=abbr[j]
j+=1
if number:
i+=int(number)
if word[i]!=abbr[j]:
return False
i+=1
j+=1
return True
def validWordAbbreviation(word: str, abbr: str) -> bool:
"""
Check if abbreviation is valid for the given word.
Time Complexity: O(n) where n is the length of abbr
Space Complexity: O(1)
"""
i = 0 # pointer for word
j = 0 # pointer for abbr
while i < len(word) and j < len(abbr):
if abbr[j].isdigit():
# Check for leading zero (invalid)
if abbr[j] == '0':
return False
# Parse the complete number
num = 0
while j < len(abbr) and abbr[j].isdigit():
num = num * 10 + int(abbr[j])
j += 1
# Skip 'num' characters in word
i += num
else:
# Letter must match
if abbr[j] != word[i]:
return False
i += 1
j += 1
# Both pointers should reach the end
return i == len(word) and j == len(abbr)
n+m time 1 space