假设给我们两个词.
w1 = "extrapolation"
w2 = "among"
Step 1: Convert each of these strings to an array of characters个
a1 = w1.chars
#=> ["e", "x", "t", "r", "a", "p", "o", "l", "a", "t", "i", "o", "n"]
a2 = w2.chars
#=> ["a", "m", "o", "n", "g"]
Step 2: Create a hash for each array that gives the index of the first instance of each unique character in the array个
def first_char_pos(a)
a.each_with_index.with_object({}) do |(c,i),h|
h[c] = i unless h.key?(c)
end
end
h1 = first_char_pos(a1)
#=> {"e"=>0, "x"=>1, "t"=>2, "r"=>3, "a"=>4,
# "p"=>5, "o"=>6, "l"=>7, "i"=>10, "n"=>12}
h2 = first_char_pos(a2)
#=>{"a"=>0, "m"=>1, "o"=>2, "n"=>3, "g"=>4}
Step 3: Identify the letters to be removed from each word个
letters_to_remove = a1 & a2
#=> ["a", "o", "n"]
Step 4: Identify the indices of the letters in each word to keep个
def indices_to_keep(a, h, letters_to_remove)
a.size.times.to_a - h.values_at(*letters_to_remove)
end
idx1 = indices_to_keep(a1, h1, letters_to_remove)
#=>[0, 1, 2, 3, 5, 7, 8, 9, 10, 11]
idx2 = indices_to_keep(a2, h2, letters_to_remove)
#=> [1, 4]
Step 5: Identify, in order, the letters in each word to keep个
s1 = a1.values_at(*idx1)
#=> ["e", "x", "t", "r", "p", "l", "a", "t", "i", "o"]
s2 = a2.values_at(*idx2)
#=> ["m", "g"]
Step 6: Form the desired string个
s1.join + s2.join
#=> "extrplatiomg"
这与所需的字符串不同,后者为"extrpolatimg"
.原因是我删除了要删除的每个字母的第一个实例,而所需的字符串是通过删除每个字符串的第一个"a"
和最后一个"o"
来获得的.要么是OP在给出想要的结果时出错,要么是我不理解确定要删除字母的哪个实例的规则.
我没有提到可能出现大写字母的情况,因为我不知道在这种情况下适用的规则.