LeetCode – Longest Common Prefix (Java)

Problem

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

Analysis

To solve this problem, we need to find the two loop conditions. One is the length of the shortest string. The other is iteration over every element of the string array.

Java Solution

public String longestCommonPrefix(String[] strs) {
    if(strs==null || strs.length ==0){
        return "";
    }
 
    if(strs.length == 1){
        return strs[0];
    }
 
    int i=0;
    while(true){
        boolean flag = true;
        for(int j=1; j<strs.length; j++){
            if(strs[j].length()<=i || strs[j-1].length() <=i 
               || strs[j].charAt(i) != strs[j-1].charAt(i)){
                flag = false;
                break;
            }               
        }
 
        if(flag){
            i++;
        }else{
            break;
        }
    }
 
    return strs[0].substring(0, i);
}

17 thoughts on “LeetCode – Longest Common Prefix (Java)”


  1. {
    String[] s ={"arnan", "arp", "aril","a"};
    int pos=0;
    String common = "";
    for(int i=1;i<s.length;i++) {
    pos=0;

    if(!(common!=""&&s[i].startsWith(common))) {

    while(pos<=s[0].length()) {

    if(s[i].startsWith(s[0].substring(0, pos))) {

    common = s[0].substring(0, pos);

    }

    pos++;

    }
    }
    }
    System.out.println(common);
    }


  2. Java solution with only 2 Loops:

    public static String LongestCommonPrefix(String[] str){
    String prefix = "";
    int min = str[0].length();

    for(int i=0; i<min; i++){
    for(int j=1; j<str.length; j++){
    if(str[0].charAt(i) != str[j].charAt(i)){
    return prefix;
    }
    min = Math.min(min, str[j].length());
    }
    prefix += str[0].charAt(i);
    }
    return prefix;
    }

  3. public static String longestCommonPrefix(String[] strs) {
    TreeMap trieMap = new TreeMap();

    if (strs.length == 0) {
    return strs[0];
    }

    int minLength = strs[strs.length – 1].length();

    for (int i = 0; i strs[i].length()) {
    minLength = strs[i].length();
    }
    }

    for (int i = 0; i < strs.length – 1; i++) {
    for (int j = 0; j < strs.length – 1; j++) {
    trieMap.putAll(findCommon(strs[j], strs[j + 1], minLength));
    }
    }

    return trieMap.get(trieMap.firstKey());

    }

    private static TreeMap findCommon(String str1, String str2, int minLength) {
    TreeMap tempMap = new TreeMap();

    for (int i = 0; i < minLength; i++) {
    if ((str1.charAt(i) != str2.charAt(i)) || (str1.length() == i+1 || str2.length() == i+1)) {
    if ((str1.length() == i+1 || str2.length() == i+1)) {
    tempMap.put(str1.substring(0, i+1).length(), str1.substring(0, i+1));
    } else {
    tempMap.put(str1.substring(0, i).length(), str1.substring(0, i));
    }
    return tempMap;
    }
    }
    return tempMap;
    }

  4. If the string we pick (0) is not the shortest, the if condition will break the loops. If it is the longest prefix (exactly), then we’ll return as normal:


    public String longestCommonPrefix(String[] strs) {
    StringBuilder sb = new StringBuilder();

    if(strs == null || strs.length == 0) return sb.toString();
    if(strs.length == 1) return strs[0];

    int idx = 0;

    while(idx = s.length() || s.charAt(idx) != c) {
    //System.out.println(idx + " " + s.charAt(idx) + " " + c);
    return sb.toString();
    } // end if
    } // end for

    sb.append(strs[0].substring(idx,idx + 1));
    idx++;
    } //end while

    return sb.toString();
    } // end longestCommonPrefix

  5. Fails if the number of strings is less than the length of the smallest string.
    Setting minLen = Integer.MAX_VALUE works just fine.

  6. I have modified last part of method, I think now method became more understandable

    public static String longestCommonPrefix(String[] strs) {
    if(strs==null || strs.length==0)
    return “”;

    if(strs.length==1)
    return strs[0];

    String minString = strs[0];
    for(String str : strs)
    if(str.length() = 0; i–){
    if(str.charAt(i) != minString.charAt(i))
    minString = minString.substring(0, i);
    }
    }

    return minString;
    }


  7. public static String findLongestCommonPrefix(String... values) {
    String s1 = values[0];
    for(int i=0; i<s1.length(); i++){
    for(int j=1; j= word.length() || word.charAt(i)!=s1.charAt(i)){
    return s1.substring(0,i);
    }
    }
    }
    return s1;
    }

  8. my code in Java:

    public static String findLongestCommonPrefix(String... values) {
    if (values == null) {
    return null;
    }
    //find shortest string
    int shortestIndex = 0, len = Integer.MAX_VALUE;
    for (int i = 0; i < values.length; i++) {
    if (values[i].length() < len) {
    len = values[i].length();
    shortestIndex = i;
    }
    }
    //iterate thru shortest string and try to find prefixes in the rest of the array
    for (int i = 0; i 0) {
    newLength--;
    len = newLength;
    }
    }
    return values[shortestIndex].substring(0, len);

    }

    @Test
    public void testFindLongestCommonPrefix() throws Exception {
    assertEquals("Hell",LongestCommonPrefix.findLongestCommonPrefix("Hello", "HelloMan", "Hellio", "Hellan","Hellooooou"));
    assertEquals("Mont",LongestCommonPrefix.findLongestCommonPrefix("Monterrey", "MonteOlivos", "Montgomery", "Montreal","Montar"));
    }

  9. Scala:

    def findCommonPrefix[T](values: Seq[Seq[T]]): Seq[T] = {

    if (values.isEmpty) Seq.empty[T]

    else if (values.length == 1) values.head

    else {

    values.tail.foldLeft(values.head) {

    case (prev, next) =>

    var prefix = Seq.empty[T]

    next.takeWhile { v =>

    prefix :+= v

    prev.startsWith(prefix)

    }

    }

    }

    }

  10. public class LongestCommonPrefix {

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    String[] input = {“Hello”, “HelloMan”, “Hell”, “Hellan”};

    String result = getLongestCommonPrefix(input);

    System.out.println(“Result is ” + result);

    }

    public static String getLongestCommonPrefix(String[] input) {

    int minimumLength = Integer.MAX_VALUE;

    for(String str : input) {

    if (str.length() < minimumLength) {

    minimumLength = str.length();

    }

    }

    char[] charList = new char[minimumLength];

    for (int i = 0; i<minimumLength ; i++) {

    Character c = input[0].charAt(i);

    for(String str : input) {

    if (str.charAt(i) == c) {

    c = str.charAt(i);

    } else {

    return (new String(charList));

    }

    }

    if (c != null) {

    charList[i] = c;

    }

    }

    return (new String(charList));

    }

    }


  11. public String getLongestPrefix(ArrayList input){

    if(input==null || input.size()==0) return null;

    int minlen = Integer.MAX_VALUE;

    String shortest = null;

    // O(n) time complexity

    for(String s : input){

    if(s.length() < minlen) {

    minlen = s.length();

    shortest = s;

    }

    }

    int stop = shortest.length();

    for(int i=0;i<shortest.length();i++){

    char ch = shortest.charAt(i);

    for(String s : input){

    if(s.charAt(i) != ch){

    stop = i;

    break;

    }

    }

    }

    return shortest.substring(0,stop);

    }

  12. I vote for a Ternary tree. Minimizes space.

    class TernaryNode {
    char data;
    boolean endOfWord;
    TernaryNode low;
    TernaryNode equal;

  13. You can solve this using a Trie as well I think. This is a very back-of-the-envelope solution sketch that probably contains a bug or two:

    interface TrieNode {
    int countChildren();
    TrieNode put(char c);
    }

    String longestSubstring(String[] strs) {
    if (strs.length == 0) {
    return “”;
    }

    int maxLen = Integer.MAX_VALUE;
    TrieNode root = new TrieNode();

    for (String str : strs) {
    TrieNode n = root;

    for (int i = 0; i < str.length() && i 1) {
    maxLen = Math.min(maxLen, i);
    break;
    }
    n = n.put(c);
    }
    }

    return strs[0].substring(0, Math.min(strs[0].length(), maxLen));
    }

Leave a Comment