计算字符串中常见字符的数量和字符串向量

时间:2009-11-19 18:13:39

标签: java string

我的问题是如何计算,但不计算两次相同的字符。比较'aba'和'are'应该给出1作为结果,因为它只有一个共同的char。

这是我到目前为止的地方:

public int sameChars (Vector<String> otherStrs){
    int result = 0;
    String original = "aba";
    for (int h= 0; h< otherStrs.size(); h++) {
        String targetStr = otherStrs.get(h);
        for (int i=0; i< original.length(); i++) {
            char aux = original.charAt(i);
            for (int j=0; j< Math.min(original.length(), targetStr.length()); j++) {
                char targetAux = targetStr.charAt(j);
                if (aux == targetAux) {
                    result++;
                    break;
                }
            }
        }
    }
    return result;
}

欢迎提出意见,谢谢。

4 个答案:

答案 0 :(得分:1)

您可以从原始字符串创建字符数的哈希值。然后,对于每个目标字符串,检查它是否具有散列中具有非零值的char。这样可以防止多次扫描原始字符串。

伪代码:

For each char c in original string {
  hash[c]++
}
For each target string str {
  For each char c_ in str {
    if hash[c_] > 0 {
      result++;
    }
  }
}

答案 1 :(得分:0)

这就像家庭作业一样,所以这里只是基本的想法:你需要跟踪你已经计入两个地方的不同角色。 Set可能是一个很好的方法。在递增计数器之前,请检查您正在查看的字符是否已在该集合中。

答案 2 :(得分:0)

我不确定你的要求是什么:你想要计算在参考字符串原文中找到的不同字符的次数,这里“aba”因此是'a'和'b',在一组中找到存储在Vector otherStrs中的字符串?

如果是这种情况,我建议先将原始字符串缩减为不同的字符(查找和删除重复字符,或使用Map)。然后循环遍历Vector中的字符串并对每个字符串执行相同操作(删除重复项或使用Map),然后在每次找到共同字符时递增计数器。

出于好奇,这个计算的最终目标是什么?

答案 3 :(得分:0)

这是我的实施:

public static int commonChars(String s1, String s2) {
    if (s1 == null || s1.isEmpty())
        throw new IllegalArgumentException("Empty s1");
    if (s2 == null || s2.isEmpty())
        throw new IllegalArgumentException("Empty s2");

    char[] a1 = s1.toCharArray();
    char[] a2 = s2.toCharArray();

    Arrays.sort(a1);
    a1 = removeDups(a1);
    Arrays.sort(a2);
    a2 = removeDups(a2);

    int count = 0;

    for (int i = 0, j = 0; i < a1.length && j < a2.length;) {
        if (a1[i] == a2[j]) {
            i++;
            j++;
            count++;
        }
        else if (a1[i] > a2[j]) 
            j++;
        else
            i++;
    }

    return count;
}

public static char[] removeDups(char[] array) {
    char[] aux = new char[array.length];
    int c = 1;
    aux[0] = array[0];
    for (int i = 1 ; i < array.length; i++) {
        if (array[i] != array[i-1])
            aux[c++] = array[i];
    }
    return Arrays.copyOf(aux, c);
}
相关问题