gpt4 book ai didi

ruby - 如何返回 Ruby 中两个单独字符串之间的不常见字符?

转载 作者:行者123 更新时间:2023-12-02 19:13:31 24 4
gpt4 key购买 nike

我一直在致力于编码挑战,以返回两个单独字符串之间的不常见字符。然而我并没有很幸运地弄清楚这一点。我尝试了许多在谷歌搜索时发现的方法,但没有一个非常有效。然而我确实遇到了hash mapping方法,但示例仅包括 C++、Python、C — 由于 Ruby 是我的第一种编程语言,因此很难尝试在不犯错误的情况下翻译如此复杂的挑战。

我并不急于解决这个编码挑战,而是希望获得一些关于其他人认为可能值得我阅读的反馈,以便成功解决这个问题。

这是我当前的代码,请不要想太多,我知道它与应有的距离还很远:

# Find concatenated string  
# with uncommon characters of given strings
def solve(a,b)
res = "" # result
map = {}

# store all characters of b in map
[a,b].each.map{| character, element | for characters(1..26) << element[+1]
}
# Find characters of a that are not
# present in b and append to result

# Find characters of b that are not
# present in a

return res
end

这是我正在尝试执行的示例测试用例,click here卡塔挑战赛的链接:

solve("xyab","xzca") = "ybzc" 
--The first string has 'yb' which is not in the second string.
--The second string has 'zc' which is not in the first string.

最佳答案

我将字符串视为 arrays of characters 。您可以轻松找到数组之间的差异:

def solve(a, b)
first_array = a.chars
second_array = b.chars
((first_array - second_array) + (second_array - first_array)).uniq.join
end

另一种方法是使用Set :

require 'set'

def solve(a, b)
(b.chars.to_set ^ a.chars.to_set).to_a.join
end

UPD uniq 已按照@3limin4t0r 的建议添加到第一种方法中。

关于ruby - 如何返回 Ruby 中两个单独字符串之间的不常见字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63958024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com