簡體   English   中英

如何識別兩個字符串之間的公共字符數?

[英]How to identify the number of common character between two strings?

給定 2 個字符串 str1 和 str2 作為輸入,返回 str1 和 str2 中位於相同位置的字符的計數。

樣本輸入 #1

計數(“紐約”,“新德里”)

示例輸出 #1

4

因為這兩個字符串共享相同的四個前導字符:“New”

樣本輸入 #2

計數(“犀牛”,“河馬”)

示例輸出 #2

2

因為“O”占據第四位置和“S”在兩個串的第11位。

我的方法

@編輯

public int count(String str1, String str2)
{
    int p=0;
    int k=0;
    int count=0;
    int l1=str1.length();
    int l2=str2.length();
    if(l1>=l2)
    {
     while(k<l2)
     {
         char ch1=str1.charAt(p);
         char ch2=str2.charAt(k);
    
            if(ch1==ch2)
            {
                p++;
                k++;
                count++;
            }
            else
            {
                p++;
                k++;
                
            }
      }         
     }
     else
     {
         char ch1=str1.charAt(p);
         char ch2=str2.charAt(k);
    
         while(k<l1)
         {
             
            if(ch1==ch2)
            {
                p++;
                k++;
                count++;
            }
            else
            {
                p++;
                k++;
                
            }
          }         
      }
   return count;
}   

參數 實際輸出 預期輸出

'Trisect''類' 0 1

我現在得到正確的輸出。

感謝你

使用單個循環可以更有效地完成此操作。 找到帶有解決方案的以下代碼:-

class GetCount {

public static void main(String args[]) {
    String myString = "rhinoceroses";
    String myString1 = "hippopotamus";

    count(myString, myString1);
}

/**
 * @param myString
 * @param myString1
 */
private static void count(String myString, String myString1) {
    int i = 0;
    int count = 0;
    int length = myString.length() < myString1.length() ? myString.length() : myString1.length();
    while(i < length) {
        if(myString.charAt(i) == myString1.charAt(i)) {
            count++;
        }
        i++;
    }
    System.out.println("Count is :: " + count);

}

}

這是一個緊湊的解決方案,非常容易理解。


解決方案

public static int count(String s1, String s2){
    int count = 0;
    for (int i = 0 ; i < (s1.length() > s2.length() ? s2 : s1).length() ; i++){
        count += s1.charAt(i) == s2.charAt(i) ? 1 : 0;
    }
    return count;
}

輸入

public static void main(String[] args) {
    System.out.println(
            "New York, New Delhi : " 
            + count("New York", "New Delhi"));

    System.out.println(
            "Rhinoceroses, Hippopotamus : " 
            + count ("Rhinoceroses", "Hippopotamus"));
}

輸出

New York, New Delhi : 4
Rhinoceroses, Hippopotamus : 2

之前提供的解決方案是無用的,因為它們只有在字符順序相同時才有效。 這是我的解決方案:

private int commonCharacterCount(String s1, String s2) {
    int counter = 0;

    List<Character> list = new LinkedList<>();
    for (char aChar : s1.toCharArray()) {
        list.add(aChar);
    }

    for (char c : s2.toCharArray()) {
        if (list.contains(c)) {
            list.remove(Character.valueOf(c));
            counter++;
        }
    }
    return counter;
}

不客氣 :)

你也可以做這樣的事情。 (嘗試一下) -

public int count(String s1, String s2) {
    int result=0;
    char[] ch1=s1.toCharArray();
    char[] ch2=s2.toCharArray();

    if(ch1.length>ch2.length){
    for(int i=0;i<ch2.length;i++){
        if(ch1[i]==ch2[i]){
            result++;
        }
    }
    }
    else{
        for(int i=0;i<ch1.length;i++){
            if(ch2[i]==ch1[i]){
                result++;
            }
        }
    }
    return result;
}

打字稿解決方案。 保證約束:1 ≤ s1.length ≤ 15, 1 ≤ s2.length ≤ 15

function commonCharacterCount(s1: string, s2: string): number {
    let count = 0;
    let s_1 = s1.split("");
    let s_2 = s2.split("");

    for (let i = 0; i < s_1.length; i++) {
        for (let j = 0; j < s_2.length; j++) {
            if (s_1[i] == s_2[j]) {
                count++;
                s_2.splice(j, 1);
                break;
            }
        }
    }
    return(count);
}

由於您需要計算相同位置的字符數,因此我們可以在每次迭代(字符串位置)的單個循環中檢查字符是否相等。 並且迭代次數應該是str1str2的最小長度(也許我們可以將Math.min(str1.length(), str2.length())提取到一個變量中)。 我使用循環條件中的最小字符串長度將if - else分支從您的解決方案壓縮為單個循環。

public int countCommonChars(String str1, String str2) {
  int commonCharsNumber = 0;
  for(int i=0; i< Math.min(str1.length(), str2.length()); i++) {
    if (str1.charAt(i) == str2.charAt(i)) {
      commonCharsNumber++;
    }
  }
  return commonCharsNumber;
}
int commonCharacterCount(String s1, String s2) {

    Map<String, Integer> mapOfString1 = getOcuurances(s1);
    Map<String, Integer> mapOfString2 = getOcuurances(s2);

    int counter = 0;

    for (Map.Entry<String, Integer> entry : mapOfString2.entrySet()) {
        if (mapOfString1.get(entry.getKey()) != null) {
            if (mapOfString1.get(entry.getKey()) > entry.getValue()) {
                counter += entry.getValue();
            } else {
                counter += mapOfString1.get(entry.getKey());
            }
        }

    }
    return counter;
}

public Map<String, Integer> getOcuurances(String s) {
    Map<String, Integer> hashMap = new HashMap<>();
    String[] strings = s.split("");
    for (int i = 0; i < strings.length; i++) {
        if (hashMap.containsKey(strings[i])) {
            hashMap.put(strings[i], hashMap.get(strings[i]) + 1);
        } else {
            hashMap.put(strings[i], 1);
        }
    }
    return hashMap;
}
int count(String s1, String s2) {
    Map<Character, Integer> charCountMap1 = getCharacterCount(s1);
    Map<Character, Integer> charCountMap2 = getCharacterCount(s2);

    return charCountMap1.entrySet().stream().map(charCountEntry ->
        Math.min(charCountEntry.getValue(), charCountMap2.getOrDefault(charCountEntry.getKey(), 0))
    ).collect(Collectors.summingInt(value -> value));
}

private Map<Character, Integer> getCharacterCount(String str) {
    Map<Character, Integer> charCountMap = new HashMap<>();
    for (int i = 0; i < str.toCharArray().length; i++) {
        Integer count = charCountMap.getOrDefault(str.charAt(i), 0);
        charCountMap.put(str.charAt(i), ++count);
    }
    return charCountMap;
}

雖然已經有一個公認的答案,但我覺得答案不夠簡潔,因此我給出了我的(尚未編譯,請將其視為偽代碼)

public static int count(String s1, String s2) {
    if (s1 == null || s2==null ||s1.isEmpty() || s2.isEmpty()) {
        return 0;
    }
    int minLength = Math.min(s1.length(), s2.length());
    int count = 0;
    for (int i < 0; i < minLength; ++i) {
        if (s1.charAt(i) == s2.charAt(i)) {
            ++count;
        }
    }
    return count;
}
public int count(String str1, String str2) {
    int result = 0;
    if (str1.length() == 0 || str2.length() == 0)
        return result;
    if (str1.length() > str2.length()) {
        for (int i = 0; i < str2.length(); i++) {
            if (str2.charAt(i) == str1.charAt(i))
                result++;
        }
    }
    else {
        for (int i = 0; i < str1.length(); i++) {
            if (str1.charAt(i) == str2.charAt(i))
                result++;
        }
    }
    return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM