From b272ec7d8154268b3659dae2d51fd2c36fbe6f5b Mon Sep 17 00:00:00 2001 From: Shivani Jha <122033027+shivanijhaa@users.noreply.github.com> Date: Sun, 8 Oct 2023 14:50:50 +0530 Subject: [PATCH] Create longest_name.java --- longest_name.java | 70 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 longest_name.java diff --git a/longest_name.java b/longest_name.java new file mode 100644 index 0000000..178c3fb --- /dev/null +++ b/longest_name.java @@ -0,0 +1,70 @@ +// Java code for the above approach +import java.io.*; +import java.util.*; + +class GFG +{ + + // Function to display longest names + // contained in the array + public static ArrayList solve(String arr[], + int N) + { + + // Edge Case + if (N == 0) { + ArrayList temp + = new ArrayList(); + return temp; + } + + // Initialize Max + int Max = arr[0].length(); + + // Create an arraylist res + ArrayList res = new ArrayList(); + + // Insert first element in res + res.add(arr[0]); + + // Traverse the array + for (int i = 1; i < N; i++) { + + // If string with greater length + // is found + if (arr[i].length() > Max) { + Max = arr[i].length(); + res.clear(); + res.add(arr[i]); + } + + // If string with current max length + else if (arr[i].length() == Max) { + res.add(arr[i]); + } + } + + // Return the final answer + return res; + } + + // Driver Code + public static void main(String[] args) + { + String arr[] = { "GeeksforGeeks", "FreeCodeCamp", + "StackOverFlow", "MyCodeSchool" }; + + int N = arr.length; + + // Function call + ArrayList v = solve(arr, N); + + // Printing the answer + for (String i : v) { + System.out.print(i + " "); + } + System.out.println(); + } +} + +// This code is contributed by Rohit Pradhan