gpt4 book ai didi

ruby - 如何计算两个字符串共有的字符数?

转载 作者:数据小太阳 更新时间:2023-10-29 07:08:55 25 4
gpt4 key购买 nike

如何计算两个字符串之间的字符交集?

例如(假设我们有一个名为 String.intersection 的方法):

"abc".intersection("ab") = 2
"hello".intersection("hallo") = 4

好的,男孩女孩们,感谢你们的大量反馈。更多示例:

"aaa".intersection("a") = 1
"foo".intersection("bar") = 0
"abc".intersection("bc") = 2
"abc".intersection("ac") = 2
"abba".intersection("aa") = 2

一些补充说明:维基百科定义 intersection如下:

Intersection of the sets A and B, denoted A ∩ B, is the set of all objects that are members of both A and B. The intersection of {1, 2, 3} and {2, 3, 4} is the set {2, 3}

最佳答案

使用String#count :

irb(main):001:0> "hello".count("hallo")
=> 4
irb(main):002:0> "abc".count("ab")
=> 2

关于ruby - 如何计算两个字符串共有的字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6073739/

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