1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/rb/word-pattern.rb
Matej Focko 2351dfd0ee
chore: unwrap one layer
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-12 14:36:00 +01:00

49 lines
1.3 KiB
Ruby

# @param {String} pattern
# @param {String} s
# @return {Boolean}
def word_pattern(pattern, s)
words = s.split
expected_words = Hash.new
expected_patterns = Hash.new
pattern.chars.zip(words).each { |pat, word|
expected_word = expected_words[pat]
expected_pattern = expected_patterns[word]
if expected_pattern == nil && expected_word == nil then
expected_patterns[word] = pat
expected_words[pat] = word
elsif word != expected_word || pat != expected_pattern then
return false
end
}
return pattern.size == words.size
end
RSpec.describe "word_pattern" do
it "finds pattern" do
expect(word_pattern("abba", "dog cat cat dog")).to be true
end
it "finds one odd word" do
expect(word_pattern("abba", "dog cat cat fish")).to be false
end
it "finds that are not the same words" do
expect(word_pattern("aaaa", "dog cat cat dog")).to be false
end
it "handles bijection correctly" do
expect(word_pattern("abba", "dog dog dog dog")).to be false
end
it "handles correctly different length of input" do
expect(word_pattern("aaa", "aa aa aa aa")).to be false
end
it "handles correctly different length of pattern" do
expect(word_pattern("aaaaa", "aa aa aa aa")).to be false
end
end