2009-11-19 83 views
1

我的問題是如何計數但不計算兩次相同的字符。就像比較'aba'和'are'一樣,結果應該是1,因爲它只有一個字符。計算字符串中的常見字符數和字符串向量

這是我到目前爲止:

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; 
} 

想法,歡迎,謝謝。

+0

功課吧? – 2009-11-19 18:34:59

回答

1

您可以從原始字符串中創建字符數的散列。然後,對於每個目標字符串,檢查它的哈希中是否有一個非零值的字符。這會阻止多次掃描原始字符串。

僞代碼:

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++; 
    } 
    } 
} 
0

這氣味像功課,所以這裏的僅僅是基本的想法:你需要保持你已經算作是在這兩個地方是鮮明的人物的軌道。一套可能是一個很好的方法來做到這一點。在增加計數器之前,請檢查您正在查看的角色是否已經在該組中。

+0

完成,謝謝。 – d0pe 2009-11-19 18:44:58

0

我不確定要了解您的要求:您是否想要計算在參考字符串原始中找到的不同字符(此處爲「aba」,因此「a」和「b」)在一組中找到的次數存儲在Vector otherStrs中的字符串?

如果是這種情況,我會建議先將原始字符串減少爲不同的字符(查找和刪除重複項或使用Map)。然後循環遍歷Vector中的字符串,並在每次找到一個字符時增加計數器之前爲每個字符串執行相同操作(刪除重複項或使用Map)。

出於好奇,這個計算的最終目標是什麼?

+0

這是一個項目的一個啞巴部分,基本上我得到一個名字,並且必須與矢量中的其他名稱進行比較,同時計算它們之間的常用字符數量,並且不會爲每個唯一字符計數超過一次。 – d0pe 2009-11-19 18:38:48

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); 
}