[Leetcode] Longest Common Prefix

Source: Internet
Author: User
Tags first string

No.14,longest Common Prefix

The input to this question is an array of strings, from which the longest common prefix is found.

Idea: Start with the first string and the second string to find the longest common prefix, compare the longest public prefix to the third string, and so on, traverse all the strings to find the last common prefix.

The optimization point is that the length of the longest public prefix must be less than or equal to the length of the shortest string, optimizing the number of comparisons.

 Public classSolution { PublicString Longestcommonprefix (string[] strs) {if(strs.length==0)            return""; if(strs.length==1)            returnStrs[0]; intLength=strs[0].length (); String prefix=strs[0];  for(inti=1;i<strs.length;i++) {length=math.min (length, strs[i].length ()); String Str=Strs[i]; intJ;  for(j=0;j<length;j++){                if(Prefix.charat (j)! =Str.charat (j)) {                     Break; }} prefix=prefix.substring (0, J); Length=math.min (length, prefix.length ()); }        returnprefix; }}

[Leetcode] 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.