java - n 个字符串中的常用字符
问题描述
我正在尝试制作一个函数来打印给定 n 个字符串中常见的字符数。(注意字符可以多次使用)
我正在努力对 n 个字符串执行此操作但是我为 2 个字符串执行了此操作,而没有任何字符重复多次。
我已经发布了我的代码。
public class CommonChars {
public static void main(String[] args) {
String str1 = "abcd";
String str2 = "bcde";
StringBuffer sb = new StringBuffer();
// get unique chars from both the strings
str1 = uniqueChar(str1);
str2 = uniqueChar(str2);
int count = 0;
int str1Len = str1.length();
int str2Len = str2.length();
for (int i = 0; i < str1Len; i++) {
for (int j = 0; j < str2Len; j++) {
// found match stop the loop
if (str1.charAt(i) == str2.charAt(j)) {
count++;
sb.append(str1.charAt(i));
break;
}
}
}
System.out.println("Common Chars Count : " + count + "\nCommon Chars :" +
sb.toString());
}
public static String uniqueChar(String inputString) {
String outputstr="",temp="";
for(int i=0;i<inputstr.length();i++) {
if(temp.indexOf(inputstr.charAt(i))<0) {
temp+=inputstr.charAt(i);
}
}
System.out.println("completed");
return temp;
}
}
3
abcaa
bcbd
bgc
3
他们可能有机会在一个字符串中多次出现相同的字符,并且您不应该消除这些字符而是检查否。他们在其他字符串中重复的次数。例如
3
abacd
aaxyz
aatre
输出应该是 2
如果我在java中得到解决方案会更好
解决方案
获取每个字符串的字符列表:
List<Character> chars1 = s1.chars() // list of chars for first string
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
List<Character> chars2 = s2.chars() // list of chars for second string
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
然后使用retainAll
方法:
chars1.retainAll(chars2); // retain in chars1 only the chars that are contained in the chars2 also
System.out.println(chars1.size());
如果您想获得唯一字符的数量,只需使用Collectors.toSet()
而不是toList()
推荐阅读
- c# - Selenium 问题关闭弹出窗口
- flutter - 覆盖 operator== 是否有助于避免重建?
- python - 如何在 Python 中结合以下理解?
- python - 如何在 docker(Azure Web App)中为 Python 导入 cv2?
- python - 在条件上接收 Python unindent 错误我认为缩进看起来正确
- node.js - 在 express 中,当满足条件时,如何路由到自定义错误模板?
- c# - 实现基于组的角色 ASP.NET MVC CORE
- python - 如何为 DataFrame 中的每一行聚合来自 ID 匹配的 N 个其他 DataFrames(在特定列上)的数据
- excel - 如何连接多个满足表格/Excel 标准的单元格?
- amazon-web-services - 通过 Athena 和/或 Glue 将 S3 数据 ETLing 到 CSV