假设我有 String x= "algorithm"
和 Stringy= "mgth"
String x
包含 String y
中的所有字母,我可以将 String y
拆分为字母列表,并循环遍历该列表查看字符串 x
是否包含字母 y[index]
,,
但我想知道是否有更有效的方法
编辑:
在 kotlin 中有一个简单的相交函数,例如:
val x="algorithm".toList()
val y="mgth".toList()
val interesct=x.intersect(y) //returns a Set of matching chars
if (y.size == interesct.size){
println("match")
}
最佳答案
用于救援的正则表达式:
String pattern = "mgth".chars()
.mapToObj(ch -> "(?=.*" + (char) ch + ")")
.collect(Collectors.joining());
// ".*(?=.*m)(?=.*g)(?=.*t)(?=.*h).*"
boolean matches = Pattern.compile(".*"+pattern+".*")
.matcher("algorithm")
.matches();
System.out.println(matches);
仅当“algorithm”
包含从目标字符串生成的模式中的所有字符时,这才会匹配。
编辑
此外,您还可以对两个字符串进行排序,并仅以 [min("mgth"), max("mgth")]
个字符值的间隔进行比较。
关于java - 文本相似度搜索算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57030232/