如何计算两个字符串共有的字符数? [英] How to calculate number of chars common to two strings?

查看:47
本文介绍了如何计算两个字符串共有的字符数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would you calculate the intersection of characters between two strings?

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

For example (assuming we would have a method called String.intersection):

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

好的,男孩和女孩,感谢您的大量反馈.更多示例:

Ok, boys and girls, thanks for your massive feedback. Some more examples:

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

还有一些注意事项:维基百科将intersection定义如下:

Some more notes: Wikipedia defines intersection as follows:

集合 A 和 B 的交集,记为 A∩B,是所有既是 A 成员又是 A 成员的对象B. {1, 2, 3} 和{2, 3, 4} 是集合 {2, 3}

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}

推荐答案

这通过了你描述的所有测试用例:

This passes all your described test cases:

class String
  def intersection(other)
    str = self.dup
    other.split(//).inject(0) do |sum, char|
      sum += 1 if str.sub!(char,'')
      sum
    end
  end
end

这篇关于如何计算两个字符串共有的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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