给定一个字符串列表,我如何确定最短的区分长度是多少?

时间:2011-08-03 17:11:46

标签: ruby

假设我有一个哈希字符串数组,例如

['a04a872ff4027233', '8cef496d2a92808c', etc.]

我想要一种优雅的方法来确定我可以用来区分替代方案的最短的统一长度子串。

E.g。如果最短长度子串是3,那么选项可以缩写为['a04','8ce'等],然后我可以稍后扩展缩写。

我需要Ruby中的解决方案。

2 个答案:

答案 0 :(得分:1)

本身不是很“优雅”,但这可行:

strings = ['a04a872ff4027233', '8cef496d2a92808c', .....]
count = 1
count += 1 while strings.map{ |item| item[0...count] }.uniq.length != strings.length

count
# => 3

strings.map{ |item| item[0...count] }
# => ['a04', '8ce', ...]

答案 1 :(得分:1)

(1...s.first.size).find {|i| !s.map {|j| j[0...i]}.uniq!}