Created
March 30, 2024 11:26
-
-
Save codertcet111/896d73c11afbc7b33787ecf4c1b1d1e7 to your computer and use it in GitHub Desktop.
Leetcode 38: count and say
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Leetcode 38: count and say | |
# @param {Integer} n | |
# @return {String} | |
def count_and_say(n) | |
return "1" if n == 1 | |
str = count_and_say(n-1) | |
str = str.split("").map {|ch| ch.to_i} | |
#str.tally.map{|k,v| "#{v}#{k}" }.join("") | |
len = str.length | |
return "1#{str[0]}" if len == 1 | |
curr_count = 1 | |
str_to_r = "" | |
(1..len-1).each do |i| | |
if str[i] == str[i-1] | |
curr_count += 1 | |
else | |
str_to_r << "#{curr_count}#{str[i-1]}" | |
curr_count = 1 | |
end | |
end | |
str_to_r << "#{curr_count}#{str[-1]}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment