Java program to find the duplicate words in a string
Example:
Input: str = "Java is Java Programming Language and C is a programming language";
Approach: Simple
Java
public class DuplicateWord {public static void main(String[] args) {String str = "Java is Java Programming Languageand C is a programming language";// Case sensitive conditionstr = str.toLowerCase();String word[] = str.split(" ");for (int i = 0; i < word.length; i++) {for (int j = i + 1; j < word.length; j++) {if (word[i].equals(word[j])) {System.out.println("Duplicate is: " + word[i]);}}}}}
Output:
Duplicate is: javaDuplicate is: isDuplicate is: programmingDuplicate is: language
Approach: Efficient
Java
import java.util.HashSet;public class DuplicateWord {public static void main(String[] args) {String str = "Java is Java Programming Languageand C is a programming language";// Case sensitive conditionstr = str.toLowerCase();String word[] = str.split(" ");HashSet<String> set = new HashSet<String>();for (int i = 0; i < word.length; i++) {if (set.contains(word[i])) {System.out.println("Duplicate is: " + word[i]);}set.add(word[i]);}}}
Output:
Duplicate is: javaDuplicate is: isDuplicate is: programmingDuplicate is: language
No comments:
Post a Comment