Leetcode LCP (Longest Common Prefix) problem

Source: Internet
Author: User
Tags first string

This is also a simple topic, but the key is test instructions understanding.
The title is in the sentence: Write a function to find the longest common prefix string amongst an array of strings.
Test instructions is a string array that finds the longest common prefix of all strings in this string array.
Note that it is a qualified prefix, not a substring.

So, the direct solution is to compare each character by the first string as a benchmark. The algorithm complexity is also obviously O (m*n), M is the number of strings, N is the longest prefix length.

The code is as follows:

classSolution { Public:stringLongestcommonprefix ( vector<string>&strs) {intLen = Strs.size ();stringPrefixif(len = =0)returnRes for(intpos =0; POS < strs[0].size (); pos++)//Longest prefix length does not exceed strs[0].size (), character-by-characters comparison{//character comparison of the corresponding position of each string             for(intK =1; K < Len; k++) {if(strs[k].size () = = pos | | strs[k][pos]! = strs[0][pos])returnRes } prefix.push_back (strs[0][pos]); }returnPrefix }};

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode LCP (Longest Common Prefix) problem

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.