14 Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

Input
["abc","abe","abdefg","abaaaa"]
Output
["ab"]

Solution)

From the given String arrays, make the first element as a longest common prefix by traversing the array and comparing. Basically, we can use String.indexOf to find the first matched index of two strings. In the case of prefix, the index should be 0. For the upper example, the first element is "abc". The second element is "abe". "abe".indexOf("abc") is not 0. In this case, we can remove the last character step by step. So, we can make the first element as "ab" by removing "c". Now, "abe".indexOf("ab") is 0. So, "ab" is the longest common prefix of "abc" and "abe". Likewise, we can repeat this operation for all other elements.

class Solution {
    public String longestCommonPrefix(String[] strs) {
        for (int i = 1; i < strs.length; i++) { // two more elements
            while (strs[i].indexOf(strs[0]) != 0) {
                strs[0] = strs[0].substring(0,strs[0].length()-1);
            }
        }
        return strs.length == 0 ? "" : strs[0];
    }
}

results matching ""

    No results matching ""