Skip to content

Commit

Permalink
Merge pull request #428 from fartem/1816_Truncate_Sentence
Browse files Browse the repository at this point in the history
2023-12-13 v. 3.7.3: added "1816. Truncate Sentence"
  • Loading branch information
fartem authored Dec 13, 2023
2 parents 21d6108 + c856782 commit 6d1da3f
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,3 +319,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
| 1800. Maximum Ascending Subarray Sum | [Link](https://leetcode.com/problems/maximum-ascending-subarray-sum/) | [Link](./lib/easy/1800_maximum_ascending_subarray_sum.rb) |
| 1805. Number of Different Integers in a String | [Link](https://leetcode.com/problems/number-of-different-integers-in-a-string/) | [Link](./lib/easy/1805_number_of_different_integers_in_a_string.rb) |
| 1812. Determine Color of a Chessboard Square | [Link](https://leetcode.com/problems/determine-color-of-a-chessboard-square/) | [Link](./lib/easy/1812_determine_color_of_a_chessboard_square.rb) |
| 1816. Truncate Sentence | [Link](https://leetcode.com/problems/truncate-sentence/) | [Link](./lib/easy/1816_truncate_sentence.rb) |
2 changes: 1 addition & 1 deletion leetcode-ruby.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ require 'English'
::Gem::Specification.new do |s|
s.required_ruby_version = '>= 3.0'
s.name = 'leetcode-ruby'
s.version = '3.7.2'
s.version = '3.7.3'
s.license = 'MIT'
s.files = ::Dir['lib/**/*.rb'] + %w[bin/leetcode-ruby README.md LICENSE]
s.executable = 'leetcode-ruby'
Expand Down
23 changes: 23 additions & 0 deletions lib/easy/1816_truncate_sentence.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# frozen_string_literal: true

# https://leetcode.com/problems/truncate-sentence/
# @param {String} s
# @param {Integer} k
# @return {String}
def truncate_sentence(s, k)
index = 0
spaces = 0
(0...s.length).each do |i|
next unless s[i] == ' '

spaces += 1

next unless spaces == k

index = i

break
end

index.zero? ? s : s[0, index]
end
13 changes: 13 additions & 0 deletions test/easy/test_1816_truncate_sentence.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# frozen_string_literal: true

require_relative '../test_helper'
require_relative '../../lib/easy/1816_truncate_sentence'
require 'minitest/autorun'

class TruncateSentenceTest < ::Minitest::Test
def test_default
assert_equal('Hello how are you', truncate_sentence('Hello how are you Contestant', 4))
assert_equal('What is the solution', truncate_sentence('What is the solution to this problem', 4))
assert_equal('chopper is not a tanuki', truncate_sentence('chopper is not a tanuki', 5))
end
end

0 comments on commit 6d1da3f

Please sign in to comment.