Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Longest Common Prefix Method 2

class Solution:
    def longestCommonPrefix(self, strs):
        result = []
        for i in zip(*strs):
            if len(set(i)) != 1:
                break
            result.append(i[0])
        return "".join(result)     

"""The zip() method returns a zip object, which is an iterator of tuples where 
the first item in each passed iterator is paired together, and then the second item in 
each passed iterator are paired together etc.
If the passed iterators have different lengths, the iterator with the least items 
decides the length of the new iterator.

set() method is used to convert any of the iterable to sequence of iterable elements 
with distinct elements, commonly called Set. 
"""                 
 
        

Task = Solution()
print("3a. ",Task.longestCommonPrefix(["flower","flow","flight"]))
print("3b. ",Task.longestCommonPrefix(["dog","racecar","car"]))
Comment

Longest Common Prefix in an Array

// Java Program to find the longest common
// prefix of the given words
public class Longest_common_prefix {
      
    // Alphabet size (# of symbols)
    static final int ALPHABET_SIZE = 26;
       
    // Trie node
    static class TrieNode
    {
        TrieNode[] children = new TrieNode[ALPHABET_SIZE];
       
        // isLeaf is true if the node represents
        // end of a word
        boolean isLeaf;
          
        // constructor
        public TrieNode() {
            isLeaf = false;
            for (int i = 0; i < ALPHABET_SIZE; i++)
                children[i] = null;
        }
    };
       
    static TrieNode root;
    static int indexs;
       
    // If not present, inserts the key into the trie
    // If the key is a prefix of trie node, just marks
    // leaf node
    static void insert(String key)
    {
        int length = key.length();
        int index;
       
        TrieNode pCrawl = root;
       
        for (int level = 0; level < length; level++)
        {
            index = key.charAt(level) - 'a';
            if (pCrawl.children[index] == null)
                pCrawl.children[index] = new TrieNode();
       
            pCrawl = pCrawl.children[index];
        }
       
        // mark last node as leaf
        pCrawl.isLeaf = true;
    }
       
    // Counts and returns the number of children of the
    // current node
    static int countChildren(TrieNode node)
    {
        int count = 0;
        for (int i=0; i<ALPHABET_SIZE; i++)
        {
            if (node.children[i] != null)
            {
                count++;
                indexs = i;
            }
        }
        return (count);
    }
       
    // Perform a walk on the trie and return the
    // longest common prefix string
    static String walkTrie()
    {
        TrieNode pCrawl = root;
        indexs = 0;
        String prefix = "";
       
        while (countChildren(pCrawl) == 1 &&
                pCrawl.isLeaf == false)
        {
            pCrawl = pCrawl.children[indexs];
            prefix += (char)('a' + indexs);
        }
        return prefix;
    }
       
    // A Function to construct trie
    static void constructTrie(String arr[], int n)
    {
        for (int i = 0; i < n; i++)
            insert (arr[i]);
        return;
    }
       
    // A Function that returns the longest common prefix
    // from the array of strings
    static String commonPrefix(String arr[], int n)
    {
        root = new TrieNode();
        constructTrie(arr, n);
       
        // Perform a walk on the trie
        return walkTrie();
    }
       
    // Driver program to test above function
    public static void main(String args[])
    {
        String arr[] = {"geeksforgeeks", "geeks",
                        "geek", "geezer"};
        int n = arr.length;
       
        String ans = commonPrefix(arr, n);
       
        if (ans.length() != 0)
            System.out.println("The longest common prefix is "+ans);
        else
            System.out.println("There is no common prefix");
    }
}
// This code is contributed by Sumit Ghosh
Comment

Longest Common Prefix

class Solution:
    def longestCommonPrefix(self, strs):
        result = ""
        
        for i in range(len(strs[0])):                       # Pick any word in the list and loop through its length. Thats the number of times youre to loop thu the list
                                                            # because your answer cant be longer in length than any word in the list
            for word in strs:                                  # loop through the words in the the list so you can use the word[i] to acces the letters of each word                
                if i == len(word) or word[i] != strs[0][i]:     # stop code by returning result if loop count(i) is same as length of your chosen word 
                    return result                               # or if theres no more similar between other words and your chosen word
            result = result + strs[0][i]                        # otherwise keep adding the similar letters that occur in same position in all the words to the result 
 
        

Task = Solution()
print(Task.longestCommonPrefix(["flower","flow","flight"]))
print(Task.longestCommonPrefix(["dog","racecar","car"]))
Comment

Longest Common Prefix

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        
    }
};
Comment

Longest Common Prefix

class Solution {
    public String longestCommonPrefix(String[] strs) {
        
    }
}
Comment

Longest Common Prefix



char * longestCommonPrefix(char ** strs, int strsSize){

}
Comment

Longest Common Prefix

public class Solution {
    public string LongestCommonPrefix(string[] strs) {
        
    }
}
Comment

Longest Common Prefix

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    
};
Comment

Longest Common Prefix

# @param {String[]} strs
# @return {String}
def longest_common_prefix(strs)
    
end
Comment

Longest Common Prefix

class Solution {
    func longestCommonPrefix(_ strs: [String]) -> String {
        
    }
}
Comment

Longest Common Prefix

class Solution {

    /**
     * @param String[] $strs
     * @return String
     */
    function longestCommonPrefix($strs) {
        
    }
}
Comment

Longest Common Prefix

function longestCommonPrefix(strs: string[]): string {

};
Comment

PREVIOUS NEXT
Code Example
Python :: histogram seaborn python 
Python :: python sleep 
Python :: how to end an infinite loop in specific time python 
Python :: Python message popup 
Python :: how to check how many digits string has in python 
Python :: how to return a missing element in python 
Python :: anaconda 
Python :: seaborrn set figsize 
Python :: django rest framework viewset perform_update 
Python :: python check if string contains substring 
Python :: python pass 
Python :: what is kernel_initializer 
Python :: how to append list in python 
Python :: string in list python 
Python :: python discord embed link 
Python :: python countdown from 20 down to 0 
Python :: ConfusionMatrixDisplay size 
Python :: python re.search() 
Python :: sorting algorithms in python 
Python :: datetime decreasing date python 
Python :: how to convert integer to binary string python 
Python :: datetime from float python 
Python :: remove element from list by index 
Python :: python extract email attachment 
Python :: get method in python 
Python :: Modify a Python interpreter 
Python :: how to make tkinter look better 
Python :: python add commas to list 
Python :: stack error: command failed: import sys; print "%s.%s.%s" % sys.version_info[:3]; 
Python :: django validators import 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =