Java [Leetcode] Longest Common Prefix

Source: Internet
Author: User
Tags first string

Small two long time no update blog, it is a sin, recently in the look at the Linux things lead to progress delays, so tonight before bedtime anger brush a problem!

Problem Description:

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

Problem Solving Ideas:

The problem is to find the longest identical front string inside all the array strings. So my idea is to first find the shortest string in the array, and then each time the comparison of the maximum loop the length of the line, so as to avoid the string subscript overflow problem. Sets the StringBuilder object to hold the same characters. Then begins the loop, for each character of the string, takes the position of the first string in the array as a reference, and if there is a string that does not match the character at that position, returns the StringBuilder object that was received, otherwise the loop continues. Finally, return the StringBuilder object that was received.

The code is as follows:

1  Public classSolution {2      PublicString Longestcommonprefix (string[] strs) {3         intLength =Integer.max_value;4StringBuilder StringBuilder =NewStringBuilder ();5         if(Strs.length = = 0 | | strs = =NULL)6             return"";7         if(Strs.length = = 1)8             returnStrs[0];9          for(inti = 0; i < strs.length; i++) {TenLength = (strs[i].length () < length)?strs[i].length (): length; One         } A         if(length = = 0) -             return""; -          for(intj = 0; J < length; J + +) { the              for(inti = 0; i < strs.length; i++) { -                 if(Strs[i].charat (j)! = Strs[0].charat (j)) -                     returnstringbuilder.tostring (); -             } +Stringbuilder.append (strs[0].charat (j)); -         } +         returnstringbuilder.tostring (); A     } at}

Java [Leetcode] Longest Common Prefix

Related Article

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.