有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何获得两个字符串中不匹配字符的计数?

我需要得到两个字符串中不匹配字符的计数。比如说

string 1 "hari", string 2 "malar"

现在我需要删除两个字符串中的重复项['a'&;r']在这两个字符串中都是常见的,因此请删除,现在字符串1包含“hi”字符串2包含“mla”

剩余计数=5

我试过这段代码,如果在同一个sting中重复/重复不可用,它可以正常工作,就像这里的'a'在字符串2中出现两次,因此我的代码不能正常工作

for (int i = 0; i < first.length; i++) {
                for (int j = 0; j < second.length; j++) {

                    if(first[i] == second[j])
                    {
                        getstrings = new ArrayList<String>();
                        count=count+1;
                        Log.d("Matches", "string char that matched "+ first[i] +"==" + second[j]);                          
                    }
                }
            }
            int tot=(first.length + second.length) - count;

先来这里,;二是指

char[] first  = nameone.toCharArray();
char[] second = nametwo.toCharArray();

这段代码在String 1 "sri" string 2 "hari"中正常工作,这里的字符串字符没有重复,因此上面的代码正常工作。帮我解决这个问题


共 (6) 个答案

  1. # 1 楼答案

    这是我的解决方案

    public static void RemoveMatchedCharsInnStrings(String first,String second)
        {
            for(int i = 0 ;i < first.length() ; i ++)
            {
                char c = first.charAt(i);
                if(second.indexOf(c)!= -1)
                {
                    first = first.replaceAll(""+c, "");
                    second = second.replaceAll(""+c, "");
                }
            }
            System.out.println(first);
            System.out.println(second);
            System.out.println(first.length() + second.length());
    
        }
    

    希望这是你需要的。如果没有,我会更新我的答案

  2. # 2 楼答案

    请尝试以下代码:

    String first = "hari";
    String second = malar;
    
    String tempFirst = "";
    String tempSecond = "";
    
    int maxSize = ((first.length() > second.length()) ? (first.length()) : (second.length()));
    
    for (int i = 0; i < maxSize; i++) {
        if (i >= second.length()) {
            tempFirst += first.charAt(i);
        } else if (i >= first.length()) {
            tempSecond += second.charAt(i);
        } else if (first.charAt(i) != second.charAt(i)) {
            tempFirst += first.charAt(i);
            tempSecond += second.charAt(i);
        }
    }
    
    first = tempFirst;
    second = tempSecond;
    
  3. # 3 楼答案

    一旦找到匹配项,您就需要break;

    public static void main(String[] args) {
            String nameone="hari";
            String nametwo="malar";
            char[] first  = nameone.toCharArray();
            char[] second = nametwo.toCharArray();
            List<String>getstrings=null;
            int count=0;
            for (int i = 0; i < first.length; i++) {
                for (int j = 0; j < second.length; j++) {
    
                    if(first[i] == second[j])
                    { 
                        getstrings = new ArrayList<String>();
                        count++; 
                        System.out.println("Matches"+ "string char that matched "+ first[i] +"==" + second[j]);  
                        break;
                    } 
                } 
            } 
            //System.out.println(count);
            int tot=(first.length-count )+ (second.length - count);
    
             System.out.println("Remaining after match from both strings:"+tot);
    
    }
    

    印刷品:

     Remaining after match from both strings:5
    
  4. # 4 楼答案

    这里你缺少两件事

    1. 在if条件下,当两个字符匹配时,需要将count增加2,而不是从两个字符串中删除一个
    2. 您需要在in条件中设置一个中断,因为您总是匹配角色的第一次出现

    在代码中做了以下两个更改,现在它会按预期打印结果

        for (int i = 0; i < first.length; i++) {
                for (int j = 0; j < second.length; j++) {
    
                    if(first[i] == second[j])
                    {                       
                        count=count+2;
                        break;
                    }
                }
            }
            int tot=(first.length + second.length) - count;
            System.out.println("Result = "+tot);
    
  5. # 5 楼答案

    如果字符匹配,只需循环两个字符串,增加计数,并从两个字符的总长度中删除这些计数

    s = 'hackerhappy'\
    t = 'hackerrank'\
    count = 0
    
    
    
    for i in range(len(s)):
        for j in range(len(t)):
           if s[i] == t[j]:
              count += 2
              break
    
    char_unmatched = (len(s)+len(t)) - count 
    

    char_unmatched包含两个字符串中不相等的字符数

  6. # 6 楼答案

    我看到了其他答案并想:一定有一种更具陈述性和可组合性的方式来做这件事! 是的,但要长得多

    public static void main(String[] args) {
        String first = "hari";
        String second = "malar";
        Map<Character, Integer> differences = absoluteDifference(characterCountOf(first), characterCountOf(second));
        System.out.println(sumOfCounts(differences));
    }
    
    public static Map<Character, Integer> characterCountOf(String text) {
        Map<Character, Integer> result = new HashMap<Character, Integer>();
        for (int i=0; i < text.length(); i++) {
            Character c = text.charAt(i);
            result.put(c, result.containsKey(c) ? result.get(c) + 1 : 1);
        }
        return result;
    }
    
    public static <K> Set<K> commonKeys(Map<K, ?> first, Map<K, ?> second) {
        Set<K> result = new HashSet<K>(first.keySet());
        result.addAll(second.keySet());
        return result;
    }
    
    public static <K> Map<K, Integer> absoluteDifference(Map<K, Integer> first, Map<K, Integer> second) {
        Map<K, Integer> result = new HashMap<K, Integer>();
        for (K key: commonKeys(first, second)) {
            Integer firstCount = first.containsKey(key) ? first.get(key) : 0;
            Integer secondCount = second.containsKey(key) ? second.get(key) : 0;
            Integer resultCount = Math.max(firstCount, secondCount) - Math.min(firstCount, secondCount);
            if (resultCount > 0) result.put(key, resultCount);
        }
        return result;
    }
    
    public static Integer sumOfCounts(Map<?, Integer> map) {
        Integer sum = 0;
        for (Integer count: map.values()) {
            sum += count;
        }
        return sum;
    }
    

    这是我更喜欢的解决方案,但时间要长得多。你已经用安卓系统标记了这个问题,所以我没有使用任何Java8功能,这会减少一点(但没有我希望的那么多)

    然而,它会产生有意义的中间结果。但它仍然很长:——