Java Exercises: Find all of the longest word in a given dictionary
Java Basic: Exercise-138 with Solution
Write a Java program to find all of the longest word in a given dictionary.
Example-1:
{
"cat",
"flag",
"green",
"country",
"w3resource"
}
Result: "w3resource"
Example-1:
{
"cat",
"dog",
"red",
"is",
"am"
}
Result: "cat", "dog", "red"
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.*;
public class Solution {
static ArrayList<String> longestWords(String[] dictionary) {
ArrayList<String> list = new ArrayList<String>();
int longest_length = 0;
for (String str : dictionary) {
int length = str.length();
if (length > longest_length) {
longest_length = length;
list.clear();
}
if (length == longest_length) {
list.add(str);
}
}
return list;
}
public static void main(String[] args) {
//String [] dict = {"cat", "flag", "green", "country", "w3resource"};
String [] dict = {"cat", "dog", "red", "is", "am"};
System.out.println("Original dictionary : "+Arrays.toString(dict));
System.out.println("Longest word(s) of the above dictionary: "+longestWords(dict));
}
}
Sample Output:
Original dictionary : [cat, dog, red, is, am] Longest word(s) of the above dictionary: [cat, dog, red]
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to find possible unique paths from top-left corner to bottom-right corner of a given grid (m x n).
Next: Write a Java program to get the index of the first number and the last number of a subarray where the sum of numbers is zero from a given array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework