题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
class Solution { public: /** * * @param strs string字符串vector * @return string字符串 */ string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) { return ""; } string res; for (int i = 0; i < strs[0].length(); ++i) { char c = strs[0][i]; for (auto &s : strs) { if (i >= s.length() || s[i] != c) { return res; } } res += c; } return res; } };
思路:以第一个字符串为基准,遍历strs并判断每个字符就行了。