Find Duplicates in String using hashing
// It is O(n) time
class DuplicatesInString {
// Asumption : All characters are in ASCII code
static void printDuplicates(String str) {
int[] frequency = new int[128];
for(int i = 0; i < str.length(); i++) {
frequency[str.charAt(i)]++;
}
System.out.println("Printing duplicates : ");
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(frequency[ch] > 1) {
System.out.println(ch + " appears " + frequency[ch] + " times.");
frequency[ch] = 0; // To avoid print duplicate result
}
}
}
public static void main (String[] args) {
String str = "Compile run your code with the CodeChef online IDE. Our online compiler"
+ "supports multiple programming languages like Python, C++, C, Kotlin,"
+ "NodeJS, and many more.";
printDuplicates(str);
}
}
Comments
Post a Comment