Longest Common Prefix

Source: Internet
Author: User
Tags first string

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

Solution1:

Idea: No ingenious method was thought of. Use recursion violence to do it hard. found that as long as the idea, recursion how to do can achieve the method ...

First alphabetical order, if the entire stringarray is empty wine directly returned empty string "", the first string is empty directly returns an empty string. Takes the first string to the first char, then iterates through the first one of each string, and updates each string at the same time, which is to subtract the first letter of each string.

If each string has the first string to the first letter, the output first letter plus recursion checks the new string array after the longest common prefix.

 Public classSolution { PublicString Longestcommonprefix (string[] strs) {arrays.sort (STRs); if(strs.length==0)        {            return""; }        if(Strs[0].length () ==0)        {            return""; }        CharCheck=strs[0].charat (0); String m=strs[0]; strs[0]=m.substring (1);  for(inti=1;i<strs.length;i++)        {            if(Check!=strs[i].charat (0))            {                return""; } String prev=Strs[i]; Strs[i]=prev.substring (1); }        returncheck+Longestcommonprefix (STRs);}}

Solution 2:

It's just a matter of checking each char on the line. Another version was made.

 Public classSolution { PublicString Longestcommonprefix (string[] strs) {if(strs==NULL|| Strs.length==0)    {        return""; }     for(intI=0;i<strs[0].length (); i++)    {         for(intj=0;j<strs.length;j++)        {            if(Strs[j].length () <=i| | Strs[0].charat (i)! =Strs[j].charat (i)) {                returnStrs[0].substring (0, i); }        }    }    returnStrs[0];}}

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.