【题目描述】Write a function to find the longest common prefix string amongst an array of strings.
找出字符串数组中的最长相同前缀字符串
【解题思路】采用BF法。首先取第一个字符串作为比较字符串,然后将该字符串的每个字符与其他字符串逐个进行比较,将所有相同的字符保存就是最终结果。
【考查内容】字符串
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
string res;
if(strs.size() == 0)
return res;
for (int j=0; j<strs[0].length(); ++j) {
for (int i=1; i<strs.size(); ++i) {
if(j >= strs[i].size() || strs[0][j] != strs[i][j])
return res;
}
res.push_back(strs[0][j]);
}
return res;
}
};