From 7a22f26a184a317b0d84bb6da7f994a0c84e57f3 Mon Sep 17 00:00:00 2001 From: fartem Date: Wed, 10 Jul 2024 08:00:17 +0300 Subject: [PATCH] 2024-07-10 v. 6.1.1: added "38. Count and Say" --- README.md | 1 + leetcode-ruby.gemspec | 2 +- lib/medium/38_count_and_say.rb | 30 ++++++++++++++++++++++++++++ test/medium/test_38_count_and_say.rb | 12 +++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 lib/medium/38_count_and_say.rb create mode 100644 test/medium/test_38_count_and_say.rb diff --git a/README.md b/README.md index 2a4e4e60..d129946a 100644 --- a/README.md +++ b/README.md @@ -476,3 +476,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/). | 33. Search in Rotated Sorted Array | [Link](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Link](./lib/medium/33_search_in_rotated_sorted_array.rb) | | 34. Find First and Last Position of Element in Sorted Array | [Link](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) | [Link](./lib/medium/34_find_first_and_last_position_of_element_in_sorted_array.rb) | | 36. Valid Sudoku | [Link](https://leetcode.com/problems/valid-sudoku/) | [Link](./lib/medium/36_valid_sudoku.rb) | +| 38. Count and Say | [Link](https://leetcode.com/problems/count-and-say/) | [Link](./lib/medium/38_count_and_say.rb) | diff --git a/leetcode-ruby.gemspec b/leetcode-ruby.gemspec index 2f68218e..0ddc4e6c 100644 --- a/leetcode-ruby.gemspec +++ b/leetcode-ruby.gemspec @@ -5,7 +5,7 @@ require 'English' ::Gem::Specification.new do |s| s.required_ruby_version = '>= 3.0' s.name = 'leetcode-ruby' - s.version = '6.1.0' + s.version = '6.1.1' s.license = 'MIT' s.files = ::Dir['lib/**/*.rb'] + %w[bin/leetcode-ruby README.md LICENSE] s.executable = 'leetcode-ruby' diff --git a/lib/medium/38_count_and_say.rb b/lib/medium/38_count_and_say.rb new file mode 100644 index 00000000..e65d6b40 --- /dev/null +++ b/lib/medium/38_count_and_say.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +# https://leetcode.com/problems/count-and-say/ +# @param {Integer} n +# @return {String} +def count_and_say(n) + return '1' if n == 1 + + str = count_and_say(n - 1) + result = [] + count = 1 + i = 1 + while i < str.length + if str[i] == str[i - 1] + count += 1 + else + result << (count + 48).chr + result << str[i - 1] + + count = 1 + end + + i += 1 + end + + result << (count + 48).chr + result << str[i - 1] + + result.join +end diff --git a/test/medium/test_38_count_and_say.rb b/test/medium/test_38_count_and_say.rb new file mode 100644 index 00000000..92248e39 --- /dev/null +++ b/test/medium/test_38_count_and_say.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require_relative '../test_helper' +require_relative '../../lib/medium/38_count_and_say' +require 'minitest/autorun' + +class CountAndSayTest < ::Minitest::Test + def test_default + assert_equal('1211', count_and_say(4)) + assert_equal('1', count_and_say(1)) + end +end