"Leetcode" Longest Common Prefix

Source: Internet
Author: User

Longest Common Prefix

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

The intention of the topic

It seems that it was not a check between pair of strings but on all the strings in the array.

For example:

{"A", "a", "B"} should give "" as there are nothing common the 3 strings.

{"A", "a"} should give "a" as a are longest common prefix in all the strings.

{"ABCA", "ABC"} AS ABC

{"AC", "AC", "a", "a"} as a.

Logic goes something like this:

Pick a character at i=0th location and compare it with the character on that location in every string.

If anyone doesn ' t has that just return ""

Else append that character on to the result.

Increment I and do steps 1-3 till the length of this string.

return result.

Make sure proper checks is maintained to avoid index out of bounds error.

Code

 Public class Solution { Public Static String Longestcommonprefix (string[] STRs) {if (STRs == NULL || Strs.length == 0)return "";String Pre = strs[0];int I = 1; while (i < strs.length) {System.out.println (Strs[i].indexof (PRE) ); while (Strs[i].indexof (PRE) != 0)Pre = pre.substring (0, pre.length () - 1);I++;}return Pre;}}

"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.