Leetcode notes: Longest Common Prefix

Source: Internet
Author: User

I. Title Description

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

Two. Topic analysis

The main idea of the topic is that given a set of strings, find the longest common prefix for all strings.

Comparing the longest common prefix of two strings, the length of the prefix must not exceed the shorter length of the two string, and the shortest string length is n , so long as the first character of the two strings is compared n .

Use a variable to prefix hold the longest public prefix of two strings, and then prefix compare the next string in the array as a new string, and so on.
In a special case, an empty string is returned directly if one of the string lengths in the array is 0 , or if the length of the current longest public prefix is evaluated 0 .

Three. Sample code

#include <iostream>#include <string>#include <vector>using namespace STD;classSolution { Public:stringLongestcommonprefix ( vector<string>&strs) {if(strs.size () = =0)return "";stringprefix = strs[0]; for(inti =1; I < strs.size (); ++i) {if(prefix.length () = =0|| Strs[i].length () = =0)return "";intLen = Prefix.length () < Strs[i].length ()? Prefix.length (): Strs[i].length ();intJ for(j =0; J < Len; ++J) {if(Prefix[j]! = Strs[i][j]) Break; } prefix = Prefix.substr (0, j); }returnPrefix }};

Four. Summary

The idea of the problem is not difficult, and there are several similar solutions, in the implementation of the need to minimize the number of comparison characters operation.

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

Leetcode notes: 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.