From 2895f3d4d1b2b44a68132088d44b23c57766ec2a Mon Sep 17 00:00:00 2001 From: ruheena-shaik Date: Mon, 3 Nov 2025 08:09:38 +0530 Subject: [PATCH] Add longestCommonPrefix method in Solution class Implement method to find the longest common prefix among an array of strings. --- string.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 string.java diff --git a/string.java b/string.java new file mode 100644 index 0000000..b6adec0 --- /dev/null +++ b/string.java @@ -0,0 +1,22 @@ +class Solution { + public String longestCommonPrefix(String[] strs) { + if (strs == null || strs.length == 0) + return ""; + + // Take the first string as the reference + String prefix = strs[0]; + + // Compare the prefix with each string in the array + for (int i = 1; i < strs.length; i++) { + // While the current string doesn't start with the prefix + while (strs[i].indexOf(prefix) != 0) { + // Shorten the prefix by one character + prefix = prefix.substring(0, prefix.length() - 1); + + // If prefix becomes empty, no common prefix exists + if (prefix.isEmpty()) return ""; + } + } + return prefix; + } +}