简体   繁体   中英

How to get the count of unmatched character in two strings?

I need to get the count of Unmatched character in two strings. for example

string 1 "hari", string 2 "malar"

Now i need to remove the duplicates from both string ['a' & 'r'] are common in both strings so remove that, now string 1 contain "hi" string 2 contain "mla" .

Remaining count = 5

I tried this code, its working fine if duplicate / repeart is not available in same sting like here 'a' come twice in string 2 so my code is didn't work properly.

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;

here first & second refers to

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

this code is working fine for String 1 "sri" string 2 "hari" here in a string character didn't repeat so this above code is working fine. Help me to solve this ?

Here is my solution,

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

    }

Hope it is what you need. if not i'll update my answer

I saw the other answers and thought: There must be a more declarative and composable way of doing this! There is, but it's far longer...

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

This is the solution I prefer - but it's lot longer. You've tagged the question with Android, so I didn't use any Java 8 features, which would reduce it a bit (but not as much as I would have hoped for).

However it produces meaningful intermediate results. But it's still so much longer :-(

Try out this code:

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;

you need to break; as soon as the match is found:

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

}

prints:

 Remaining after match from both strings:5

Two things you are missing here.

  1. In the if condition, when the two characters matches, you need to increment count by 2, not one as you are eliminating from both strings.
  2. You need to put a break in the in condition as you are always matching for the first occurrence of the character.

Made those two changes in your code as below, and now it prints the result as you expected.

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

You just need to loop over two strings if characters are matched increment the count and just remove those count from total len of two characters

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 contains the count of number of characters from both the strings that are not equal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM