topic
Write a function to find the longest common prefix string array
For example
Thinking
- A two-dimensional array corresponding to an array of strings, to find the longest prefix corresponds to the longitudinal traverse, two pointers, a current value taken away laterally, a longitudinal pointer away, the underlying elements of the array at the same lateral string pointer comparing means referring to
- Note that if there was to the end of the string has been traversed during traversal, we need to stop, do not forget this judgment conditions
Code
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
string res = "";
for(int j = 0; j<strs[0].size();++j)//j走横向
{
char c = strs[0][j];
for(int i = 0; i<strs.size(); ++i)//i走纵向
{
if(j>=strs[i].size() || strs[i][j] != c)//遇到一个字符串已遍历完
return res;
}
//每个字符串都ok就push_back到结果
res.push_back(c);
}
return res;
}
};