Untitled

 avatar
unknown
plain_text
19 days ago
757 B
3
Indexable
public class CommonPrefix {
    public static String findCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }

        String prefix = strs[0]; // Start with the first string as a reference

        for (int i = 1; i < strs.length; i++) {
            while (strs[i].indexOf(prefix) != 0) {
                prefix = prefix.substring(0, prefix.length() - 1);
                if (prefix.isEmpty()) {
                    return ""; // No common prefix
                }
            }
        }
        return prefix;
    }

    public static void main(String[] args) {
        String[] words = {"flower", "fly", "float"};
        System.out.println("Common Prefix: " + findCommonPrefix(words));
    }
}
Editor is loading...
Leave a Comment