Skip to content

Instantly share code, notes, and snippets.

@detunized
Created January 7, 2018 18:34
Show Gist options
  • Save detunized/83dc627e82ff54bcfbbc526da41b60ef to your computer and use it in GitHub Desktop.
Save detunized/83dc627e82ff54bcfbbc526da41b60ef to your computer and use it in GitHub Desktop.
LeetCode problem #91: Decode ways
# @param {String} s
# @return {Integer}
def num_decodings(s)
return 0 if s.empty?
n1 = 1
n2 = 0
i = 0
while i < s.size
next2 = s[i, 2]
if next2 == "10" || next2 == "20"
n1, n2 = 0, n1 + n2
i += 2
next
end
next1 = s[i].to_i
return 0 if next1 == 0
if i > 0
prev1 = s[i - 1].to_i
if prev1 == 1 || (prev1 == 2 && (next1 >= 1 && next1 <= 6))
n1, n2 = n1 + n2, n1
else
n1, n2 = n1 + n2, 0
end
end
i += 1
end
n1 + n2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment