This is the Java Program to Find the Number of Unique Words.
Given a string, in which various words are separated by whitespace. Print the count of the unique words present in it, that is the words whose frequency is 1.
Example:
String str =”Java is great C++ is also great”;
Output = 3
Split the string into various substrings based on the delimiter whitespace. Now find the frequency of each substring and maintain a count of substrings whose frequency is 1.
Here is the source code of the Java Program to Find the Number of Unique Words. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Find the Number of Unique Words
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class NumberOfUniqueWords {
// Function to calculate the number of unique words
static int calculateNoOfUniqueWords(String str) {
String[] words = str.split(" ");
boolean[] array = new boolean[words.length];
int j, i = 0;
int count = 0;
for (i = 0; i < words.length; i++) {
if (!array[i]) {
count++;
for (j = i + 1; j < words.length; j++) {
if (words[j].compareTo(words[i]) == 0) {
array[j] = true;
count--;
}
}
}
}
return count;
}
// Function to read input and display the output
public static void main(String[] args) {
BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
String str;
System.out.println("Enter the string");
try {
str = br.readLine();
} catch (IOException e) {
System.out.println("An I/O error occurred");
return;
}
int count = calculateNoOfUniqueWords(str);
System.out.println("Total number of unique words in \"" +
str + "\" are " + count);
}
}
1. In function calculateNoOfUniqueWords, the split method is used to split the string into various substrings, which are separated by whitespaces.
2. An array of boolean values is maintained to avoid checking the repeated substring more than once.
3. The loop for (i = 0; i < words.length; i++) is used to iterate through the array of substrings.
4. The condition if(!array[i]), checks whether the substring is already checked or not.
5. The nested loop checks if the substring array[i] is repeated or not.
6. If the substring is not repeated, the variable count is incremented.
7. Finally, the variable count is returned.
Time Complexity: O(n2) where n is the length of the string.
Case 1 (Average Case): Enter the string Java is great C++ is also great Total number of unique words in "Java is great C++ is also great" are 3 Case 2 (Best Case): Enter the string I am am I Total number of unique words in "I am am I" are 0 Case 3 (Worst Case): Enter the string We are here Total number of unique words in "We are here" are 3
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice Information Technology MCQs
- Check Programming Books
- Apply for Java Internship
- Apply for Computer Science Internship
- Practice BCA MCQs