diff --git a/problems/linked-list-cycle-ii.rb b/problems/linked-list-cycle-ii.rb new file mode 100644 index 0000000..e8d9f43 --- /dev/null +++ b/problems/linked-list-cycle-ii.rb @@ -0,0 +1,27 @@ +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val) +# @val = val +# @next = nil +# end +# end + +# @param {ListNode} head +# @return {ListNode} + +require 'set' + +def detectCycle(head) + def detectCycleRec(node, seen) + if node == nil then + return node + elsif seen.add?(node) == nil then + return node + end + + return detectCycleRec(node.next, seen) + end + + detectCycleRec(head, Set.new) +end diff --git a/problems/word-pattern.rb b/problems/word-pattern.rb new file mode 100644 index 0000000..0b10812 --- /dev/null +++ b/problems/word-pattern.rb @@ -0,0 +1,49 @@ +# @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