-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #428 from fartem/1816_Truncate_Sentence
2023-12-13 v. 3.7.3: added "1816. Truncate Sentence"
- Loading branch information
Showing
4 changed files
with
38 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
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 |
This file contains 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
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 |