LeetCode -- Longest Common Prefix, longestprefixmatch

Source: Internet
Author: User

LeetCode -- Longest Common Prefix, longestprefixmatch

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

Returns the longest common prefix of all strings.

Idea: first compare the public part of the first two strings, put the public part in the prefix, and then get the new prefix by comparing the prefix with the third one, so that the loop can be done, if the two characters are different, the system jumps out of the loop.

Public class LongestCommonPrefix {
Public static void main (String [] args ){
String [] strs = {"hello", "hello", "El "};
String prefix = strs [0];
For (int I = 1; I <strs. length; ++ I ){
Prefix = findCommonLongestPrefix (prefix, strs [I]);
}
System. out. println (prefix );
}

Public static String findCommonLongestPrefix (String prefix, String current ){
StringBuffer sb = new StringBuffer ();
Int len = prefix. length ()> current. length ()? Current. length (): prefix. length ();
For (int I = 0; I <len; ++ I ){
If (prefix. charAt (I) = current. charAt (I )){
Sb. append (prefix. charAt (I ));
} Else {
Break;
}
}
Return sb. toString ();
}
}

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.