题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
class Solution { public: /** * * @param strs string字符串vector * @return string字符串 */ string longestCommonPrefix(vector<string>& strs) { // write code here if (strs.empty()) return {}; string res; for (int i = 0; ; i++) { if (i == strs[0].size()) { return res; } auto c = strs[0][i]; for (auto& str : strs) { if (i == str.size() || str[i] != c) { return res; } } res += c; } return res; } };
- 思路:
- 1、遍历公共前缀长度
- 2、如果存在一个前缀长度超过其中一个字串,或者存在一个字串的字符不一样,跳出循环
- 3、否则把当前字符加入到结果中
- 时间复杂度:O(nm)
- 空间复杂度:O(1)