首页 > 解决方案 > 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中得到解决方案会更好

标签: javaarraysstringmultidimensional-array

解决方案


获取每个字符串的字符列表:

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()


推荐阅读