- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count the Number of matching characters in a pair of Java string
In order to find the count of matching characters in two Java strings the approach is to first create character arrays of both the strings which make comparison simple.After this put each unique character into a Hash map.
Compare each character of other string with created hash map whether it is present or not in case if present than put that character into other hash map this is to prevent duplicates.In last get the size of this new created target hash map which is equal to the count of number of matching characters in two given strings.
Example
import java.util.HashMap; public class MatchingCharacters { public static void main(String[] args) { String str1 = "abcccdef"; String str2 = "dfgterf"; char[] arr = str1.toCharArray(); char[] arr2 = str2.toCharArray(); HashMap<Character,Integer> hMap = new HashMap<>(); HashMap<Character,Integer> hMap2 = new HashMap<>(); for(int i = 0 ; i < arr.length ; i++) { if(!hMap.containsKey(arr[i])) { hMap.put(arr[i],1); } } for(int i = 0 ;i <arr2.length ;i++) { if(hMap.containsKey(arr2[i])) { hMap2.put(arr2[i],1); } } System.out.println("Number of matching characters in a pair of Java string is : " + hMap2.size()); } }
Output
Number of matching characters in a pair of Java string is : 3
Advertisements