[Leetcode] [Java] Longest Common Prefix

Source: Internet
Author: User

Topic:

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

Test instructions

Write a function that finds the longest common substring in a set of arrays.

Algorithm Analysis:

You need to build a double loop. The first layer is the length of the shortest substring, and the other layer iterates through each member of the string array.

Brute force idea, with the first string as the standard, for each string starting from the first character, to see if it is consistent with the standard, if different, then jump out of the loop to return the current result, or continue the next character.

AC Code:

Public String Longestcommonprefix (string[] strs)     {        if (STRs = = NULL | | strs.length = 0)            return "";             int minlen=integer.max_value;        for (String str:strs)        {            if (Minlen > Str.length ())                Minlen = Str.length ();//Find the shortest substring in these strings        }        if ( Minlen = = 0) return "";             for (int j=0; j<minlen; j + +)        {            char prev= ' 0 ';            for (int i=0; i<strs.length; i++)            {                if (i==0)                 {                    prev = Strs[i].charat (j);//The first character of a string is only tested at a time                    continue;                }                     if (Strs[i].charat (j)! = prev)//If all strings are equal, remove a character and, if not equal, return the public prefix                {return strs[i] that precedes the character                    . SUBSTRING (0, j);             }} Return strs[0].substring (0,minlen);//All strings are prefixed equal to the shortest string length    }


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] Longest Common Prefix

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.