How do you check if one array is a subsequence of another?

后端 未结 4 1164
南旧
南旧 2020-12-21 09:44

I\'m looking to explore different algorithms, both recursive and dynamic programming, that checks if one arrayA is a subsequence of arrayB. For example,

arra         


        
4条回答
  •  悲哀的现实
    2020-12-21 10:29

    Here is an example in Ruby:

    def sub_seq?(a_, b_)
      arr_a = [a_,b_].max_by(&:length);
      arr_b = [a_,b_].min_by(&:length);
      arr_a.select.with_index do |a, index|
        arr_a.index(a) &&
        arr_b.index(a) &&
        arr_b.index(a) <= arr_a.index(a)
      end == arr_b
    end
    
    arrayA = [1, 2, 3] 
    arrayB = [5, 6, 1, 7, 2, 9, 3]
    
    puts sub_seq?(arrayA, arrayB).inspect #=> true
    

提交回复
热议问题