Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Counting total number characters that have a duplicate within a string (i.e. \"g

ID: 655403 • Letter: C

Question

Counting total number characters that have a duplicate within a string (i.e. "gigi the gato" would result in 7 (g x 3 + i x 2 + t x 2)

Create an algorithm to solve the problem

Identify the factors that would influence the running time, and which can be known before the algorithm or code is executed. Assign names (such as n) to each factor.

Identify the operations that must be counted. You need not count every statement separately. If a group of statements always executes together, treat the group as a single unit. If a method is called, and you do not know the running time of that method, count it as a single operation.

Count the operations performed by the algorithm or code. Express the count as a function of the factors you identified in Step 2. If the count cannot be expressed as a simple function of those factors, define the bounds that can be placed on the count: the best case (lower bound) and worst case (upper bound).

Determine what the Best Case Inputs are, and the Worst Case Inputs are, and the efficiency of your implementation

Transform your count formula into big-O notation by:

Explanation / Answer

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

public class DuplicateCharsInString {

public void findDuplicateChars(String str){

Map<Character, Integer> dupMap = new HashMap<Character, Integer>();
char[] chrs = str.toCharArray();
for(Character ch:chrs){
if(dupMap.containsKey(ch)){
dupMap.put(ch, dupMap.get(ch)+1);
} else {
dupMap.put(ch, 1);
}
}
Set<Character> keys = dupMap.keySet();
for(Character ch:keys){
if(dupMap.get(ch) > 1){
System.out.println(ch+"--->"+dupMap.get(ch));
}
}
}

public static void main(String a[]){
DuplicateCharsInString dcs = new DuplicateCharsInString();
dcs.findDuplicateChars("Java2Novice");
}
}