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