Searching...
Thursday, 8 December 2016

Algorithm and program to find out duplicate character in a String

23:52

Algorithm

1)Create a hashMap to store character and its count
2)Convert String in to a char[] Array using toCharArray() method
3)Iterate the Character Array
4)Check the character is present in the map, if present increment the count
5)If character not there put the count as 1

Program

package com.vinod.test;

import java.util.HashMap;
import java.util.Map;

/**
 * Java program to idnentfy duplicate charactors in a string
 *
 *
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindDuplicateCharactorInString {

    public static void main(String[] args) {
        
        Map<Character, Integer> duplicateMap = new HashMap<Character, Integer>();
        String str="My name is Vinod";
        char[] chrs = str.toCharArray();
        for(Character ch:chrs){
            if(duplicateMap.containsKey(ch)){
                duplicateMap.put(ch, duplicateMap.get(ch)+1);
            } else {
                duplicateMap.put(ch, 1);
            }
        }
        duplicateMap.forEach((k,v)->System.out.println("Charactor : " + k + " Count : " + v));

       
    }

}

Output

Charactor :   Count : 3
Charactor : a Count : 1
Charactor : s Count : 1
Charactor : d Count : 1
Charactor : e Count : 1
Charactor : V Count : 1
Charactor : y Count : 1
Charactor : i Count : 2
Charactor : M Count : 1
Charactor : m Count : 1
Charactor : n Count : 2
Charactor : o Count : 1

 

 

 

 

0 comments: