From 519303edd663d3bc3896476e8c2334dad540077b Mon Sep 17 00:00:00 2001 From: Dinki Yaduwanshi <91734640+Dinki-Yaduwanshi@users.noreply.github.com> Date: Wed, 25 Oct 2023 14:59:18 +0530 Subject: [PATCH] Create common_prefix.java Signed-off-by: Dinki Yaduwanshi <91734640+Dinki-Yaduwanshi@users.noreply.github.com> --- 16_FirstContribution/common_prefix.java | 44 +++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 16_FirstContribution/common_prefix.java diff --git a/16_FirstContribution/common_prefix.java b/16_FirstContribution/common_prefix.java new file mode 100644 index 0000000..b7d314e --- /dev/null +++ b/16_FirstContribution/common_prefix.java @@ -0,0 +1,44 @@ +/*Write a function to find the longest common prefix string amongst an array of strings. + +If there is no common prefix, return an empty string "". + + + +Example 1: + +Input: strs = ["flower","flow","flight"] +Output: "fl" +Example 2: + +Input: strs = ["dog","racecar","car"] +Output: "" +Explanation: There is no common prefix among the input strings. + + +Constraints: + +1 <= strs.length <= 200 +0 <= strs[i].length <= 200 +strs[i] consists of only lowercase English letters.*/ + +//Solution: + +import java.util.Arrays; +class Solution { + public String longestCommonPrefix(String[] strs) { + if(str==null){ + return ""; + } + + Arrays.sort(strs); + String smallest=str[0]; + String largest=str[str.length-1]; + String ans=""; + + for(int i=0;i