-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuplicateWordFinder.java
More file actions
53 lines (47 loc) · 1.52 KB
/
DuplicateWordFinder.java
File metadata and controls
53 lines (47 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.lang.UnsupportedOperationException;
import java.util.Scanner;
import java.util.Hashtable;
public class DuplicateWordFinder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// parse the number of strings
int numStrings = Integer.parseInt(sc.nextLine());
// parse each string
String[] stringsArray = new String[numStrings];
for (int i = 0; i < numStrings; i++) {
stringsArray[i] = sc.nextLine();
}
// print whether there are duplicates
System.out.println(hasDuplicates(stringsArray));
}
private static boolean hasDuplicates(String[] stringsArray) {
/*
* Given an array of strings
* Returns true if there are no duplicates in the array
* Returns false if there are duplicates in the array
* Should have a linear time complexity
* The best datastructure is a hashset
*/
Hashtable<String, Integer> uniqueWords = new Hashtable<String, Integer>();
for (int i = 0; i < stringsArray.length; i++) {//iterate through stringsArrayElements
if (uniqueWords.put(stringsArray[i], 1) != null) { //put returns the previous value, if it was assigned then it is a duplicate
return true;
}
}
return false;
}
/*
* Hash Set Implementation:
* Set<String> uniqueWords = new HashSet<String>();
* for (int i = 0; i < stringsArray.length; i++) {
* if (uniqueWords.contains(stringsArray[i]){
* return true;
* }
* else {
* uniqueWords.add(stringsArray[i];
* }
* }
* return false;
*
*/
}