博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Longest Common Prefix
阅读量:4680 次
发布时间:2019-06-09

本文共 728 字,大约阅读时间需要 2 分钟。

 

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

思路:这道题其实很简单。只不过一开始我就想复杂了,一看求Longest,就联想到DP。然后又联想到Set来求交并。

后来,突然想到,其实一个string就能解决。

:Prefix的最长长度,是由匹配度最低的那个string来决定的。

假定A,B,C三个string,从前往后遍历vector的话,则一定满足len(prefix(A,B)) >= len(prefix(A,B,C))

所以用一个string类型的res来记录就可以了。

注意:返回空str,不能用NULL

几乎是bug free,很开心

class Solution {public:    string longestCommonPrefix(vector
& strs) { //check validation string res; if(strs.empty()) return res; //check special case or bound size_t n=strs.size(); if(n==1) return strs[0]; res=strs[0]; string cur; for(int i=1;i

 

转载于:https://www.cnblogs.com/renrenbinbin/p/4438874.html

你可能感兴趣的文章