最长的共同preFIX和数组的后缀 [英] Longest common prefix and suffix of arrays

查看:143
本文介绍了最长的共同preFIX和数组的后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是获得最长公共preFIX(子阵列从原始的索引0开始)和后缀(子阵列,与原来的索引-1结束时)两个阵列的最佳方法?例如,给定两个数组:

What is the best way to get the longest common prefix (sub-array that starts from index 0 of the original) and suffix (sub-array that ends with index -1 of the original) of two arrays? For example, given two arrays:

[:foo, 1, :foo, 0, nil, :bar, "baz", false]
[:foo, 1, :foo, 0, true, :bar, false]

这些阵列的最长的共同preFIX是:

the longest common prefix of these arrays is:

[:foo, 1, :foo, 0]

和这些阵列的最长公共后缀是:

and the longest common suffix of these arrays is:

[false]

在索引0 / -1的元素在原数组不同,那么普通preFIX /后缀应该是一个空数组。

When the elements at index 0/-1 differs in the original arrays, then the common prefix/suffix should be an empty array.

推荐答案

一个可能的解决方案:

a1 = [:foo, 1, 0, nil, :bar, "baz", false]
a2 = [:foo, 1, 0, true, :bar, false]

a1.zip(a2).take_while { |x, y| x == y }.map(&:first)
#=> [:foo, 1, 0]

反向输入数组和输出数组发现一个共同的后缀:

Reversing the input arrays and the output array finds a common suffix:

a1.reverse.zip(a2.reverse).take_while { |x, y| x == y }.map(&:first).reverse
#=> [false]

边缘情况:拉链填充用参数数组值:

a1 = [true, nil, nil]
a2 = [true]

a1.zip(a2).take_while { |x, y| x == y }.map(&:first)
#=> [true, nil, nil]

这可以通过截断初始阵列到第二阵列的长度来避免:

This can be avoided by truncating the initial array to the second array's length:

a1[0...a2.size].zip(a2).take_while { |x, y| x == y }.map(&:first)

这篇关于最长的共同preFIX和数组的后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆