diff --git a/README.md b/README.md index 1984f94d..93daa07e 100644 --- a/README.md +++ b/README.md @@ -627,6 +627,7 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/). | 823. Binary Trees With Factors | [Link](https://leetcode.com/problems/binary-trees-with-factors/) | [Link](./lib/medium/823_binary_trees_with_factors.rb) | [Link](./test/medium/test_823_binary_trees_with_factors.rb) | | 841. Keys and Rooms | [Link](https://leetcode.com/problems/keys-and-rooms/) | [Link](./lib/medium/841_keys_and_rooms.rb) | [Link](./test/medium/test_841_keys_and_rooms.rb) | | 852. Peak Index in a Mountain Array | [Link](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [Link](./lib/medium/852_peak_index_in_a_mountain_array.rb) | [Link](./test/medium/test_852_peak_index_in_a_mountain_array.rb) | +| 856. Score of Parentheses | [Link](https://leetcode.com/problems/score-of-parentheses/) | [Link](./lib/medium/856_score_of_parentheses.rb) | [Link](./test/medium/test_856_score_of_parentheses.rb) | ### Hard diff --git a/leetcode-ruby.gemspec b/leetcode-ruby.gemspec index 44e245c6..965adba9 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 = '7.6.6' + s.version = '7.6.7' s.license = 'MIT' s.files = ::Dir['lib/**/*.rb'] + %w[README.md] s.executable = 'leetcode-ruby' diff --git a/lib/medium/856_score_of_parentheses.rb b/lib/medium/856_score_of_parentheses.rb new file mode 100644 index 00000000..969b49a7 --- /dev/null +++ b/lib/medium/856_score_of_parentheses.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +# https://leetcode.com/problems/score-of-parentheses/ +# @param {String} s +# @return {Integer} +def score_of_parentheses(s) + stack = [0] + s.each_char do |c| + if c == '(' + stack << 0 + else + a = stack.delete_at(stack.size - 1) + b = stack.delete_at(stack.size - 1) + + stack << b + [2 * a, 1].max + end + end + + stack.last +end diff --git a/test/medium/test_856_score_of_parentheses.rb b/test/medium/test_856_score_of_parentheses.rb new file mode 100644 index 00000000..dec6265b --- /dev/null +++ b/test/medium/test_856_score_of_parentheses.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require_relative '../test_helper' +require_relative '../../lib/medium/856_score_of_parentheses' +require 'minitest/autorun' + +class ScoreOfParenthesesTest < ::Minitest::Test + def test_default_one + assert_equal( + 1, + score_of_parentheses( + '()' + ) + ) + end + + def test_default_two + assert_equal( + 2, + score_of_parentheses( + '(())' + ) + ) + end + + def test_default_three + assert_equal( + 2, + score_of_parentheses( + '()()' + ) + ) + end +end