DEV Community

Yongchang He
Yongchang He

Posted on • Edited on

2 2 1

Finding the longest common prefix string amongst an array of strings

Leetcode problem 14. Longest Common Prefix

Question:

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 "".

This is a solution from leetcode:

Approach 1: horizontal scanning

public class LongestCommonPrefix {
    public static String longestCommonPrefix(String[] strs) {
        // if the length of the string array is zero, return "";
        if (strs.length == 0) {
            return "";
        }
        // Name the first element in string array as prefix;
        String prefix = strs[0];

        //Loop from the second element in "strs" to the last one
        for (int i = 1; i < strs.length; i++) {
            // If the current element contains the prefix, move to the
            // next element and do the comparison again with the prefix
            while (strs[i].indexOf(prefix) != 0) {
                // Chop down the tail character of prefix
                prefix = prefix.substring(0, prefix.length() - 1);
                // Return "" when prefix is emply
                if (prefix.isEmpty()) {
                    return "";
                }
            }
        }
        return prefix;
    }
    // Test
    public static void main(String[] args) {
        // Array of strings
        String[] res = {"English", "Engli", "EnE"};
        String result = longestCommonPrefix(res);
        // Show result
        System.out.println(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs