-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestWordDictionary.java
More file actions
38 lines (30 loc) · 1.41 KB
/
Copy pathLongestWordDictionary.java
File metadata and controls
38 lines (30 loc) · 1.41 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
import java.util.*;
public class LongestWordDictionary {
// Function to find and return the longest words in the given dictionary
static ArrayList longestWords(String[] dictionary) {
ArrayList list = new ArrayList();
int longest_length = 0;
// Iterate through each word in the dictionary
for (String str : dictionary) {
int length = str.length();
// Check if the current word is longer than the previously found longest word(s)
if (length > longest_length) {
longest_length = length;
list.clear(); // Clear the list as a new longest word is found
}
// If the current word has the same length as the longest word(s), add it to the list
if (length == longest_length) {
list.add(str);
}
}
return list; // Return the list of longest words
}
public static void main(String[] args) {
// Sample dictionary containing words
// String[] dict = {"cat", "flag", "green", "country", "w3resource"};
String[] dict = {"cat", "dog", "red", "is", "am"};
// Print the original dictionary and the longest word(s)
System.out.println("Original dictionary: " + Arrays.toString(dict));
System.out.println("Longest word(s) of the above dictionary: " + longestWords(dict));
}
}