Topic description
Write a function to find the longest common prefix string amongst an array of strings.
Title:
Find the longest common prefix of multiple strings.
analyze:
Judge one by one.
Implementation code:
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
if (strs.empty()) return "";
for (int i = 0; i < strs[0].length(); i++) //with First string as standard
{
for (int j = 1; j < strs.size(); j++) //Compare with remaining strings
if (i >= strs[j].length() || strs[j][i] != strs[0][i]) //Inequality is encountered or the traversed position is greater than the length of a string;
return strs[0].substr(0, i) ; //return characters from 0 to i-1;
}
return strs[0];
}
};