mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 09:59:41 +01:00
50 lines
1.3 KiB
Ruby
50 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
|