2014-10-02 90 views
0

經過多次搜索沒有結果,我來請求你的幫助。我有一個小問題。我有兩個字符串:兩個字符串中有多少個字符相同

String values = "acceikoquy"; 
String values2 = "achips"; 

我會得到相同的字符數所以在這裏:

3 

你有任何想法如何做到這一點?

我的代碼:

String values = "acceikoquy"; 
String values2 = "achips"; 

int test = StringUtils.countMatches(values, values2); 

System.out.println(test); 
+0

可能重複http://stackoverflow.com/questions/3985328/checking-if-2-strings-contain-the-same-characters – 2014-10-02 09:57:55

+0

你遇到了什麼問題,當你試圖自己做這個? – EWit 2014-10-02 09:58:06

+1

你試過了什麼? – 2014-10-02 09:58:10

回答

0

事情是這樣的:

public static int sameCharsCount(String left, String right, boolean countDuplicates) { 
    if ((null == left) || (null == right)) 
     return 0; 

    HashMap<Character, Integer> occurence = new HashMap<Character, Integer>(); 

    for (int i = 0; i < left.length(); ++i) { 
     Character ch = left.charAt(i); 

     if (!occurence.containsKey(ch)) 
     occurence.put(ch, 1); 
     else 
     occurence.put(ch, occurence.get(ch) + 1); 
    } 

    int result = 0; 

    for (int i = 0; i < right.length(); ++i) { 
     Character ch = right.charAt(i); 

     if (occurence.containsKey(ch)) { 
     result += 1; 

     if (!countDuplicates || occurence.get(ch) <= 1) 
      occurence.remove(ch); 
     else 
      occurence.put(ch, occurence.get(ch) - 1); 
     } 
    } 

    return result; 
    } 

...

String values = "acceikoquy"; 
String values2 = "achips"; 

//TODO: put true or false if you want to count duplicates or not 
int result = sameCharsCount(values, values2, true); // <- returns 3 

int withDups = sameCharsCount("aaba", "caa", true); // <- 2 (two 'a' are shared) 
int noDups = sameCharsCount("aaba", "caa", false); // <- 1 (just a fact, 'a' is shared) 
+0

謝謝兄弟你救了我的命 – Julien 2014-10-02 10:34:54

0

您可以用這種方式

String values = "acxa"; 
    String values2 = "abada"; 
    int count=0; 
    List<Character> list=new ArrayList<>(); 
    List<Character> list1=new ArrayList<>(); 
    for(int i=0;i<values2.length();i++){ 
     list.add(values2.charAt(i)); 
    } 
    for(int i=0;i<values.length();i++){ 
     list1.add(values.charAt(i)); 
    } 
    ListIterator<Character> listIterator=list.listIterator(); 
    while (listIterator.hasNext()){ 
     char val=listIterator.next(); 
     if(list1.toString().contains(""+val)){ 
      count++; 
      listIterator.remove(); 
      int index=list1.indexOf(val); 
      list1.remove(index); 
     } 
    } 
    System.out.println(count); 
嘗試

出放:

2 
+0

反例:'values =「acxa」;和值2 =「阿巴達」;'預計'2'時返回'3'(如果重複不計數'1'預計) – 2014-10-02 10:39:14

+0

@DmitryBychenko是的。 fixed.Thanks指出我 – 2014-10-02 10:51:16

相關問題