"Longest Common Prefix" cpp

Source: Internet
Author: User

Topic:

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

Code:

classSolution { Public:    stringLongestcommonprefix (vector<string>&STRs) {            if(strs.size () = =0)return ""; STD::stringTmp_str = strs[0];  for(size_t i =1; I < strs.size (); ++i) {size_t J=0;  for(; J < Std::min (Tmp_str.size (), strs[i].size ()); + +j)if(Tmp_str[j]!=strs[i][j]) Break; Tmp_str= Tmp_str.substr (0, J); }            returnTmp_str; }};

Tips

Space complexity O (N1), Time complexity O (n1+n2 ...)

Each string string in the STRs is compared sequentially by 22, preserving the common prefix for this comparison to Tmp_str; the next time you compare it, you can use the last common prefix as the target string.

The benefit of this solution is that the code is relatively consice, but the spatial complexity and time complexity are not optimal.

"Longest Common Prefix" cpp

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.