Longest Common Prefix
Total Accepted: 17298 Total
Submissions: 63704My Submissions
Write a function to find the longest common prefix string amongst an array of strings.
题意:在一个字符串数组中找到最长的公共前缀
思路:
扫描数组,直到遇到一个在各个字符串不一样的字符
复杂度:时间O(n1 + n2 + ...) --> 最差的情况下,每个字符串都要扫描一遍,空间O(1)
string longestCommonPrefix(vector<string> &strs){ if(strs.size() == 0) return ""; if(strs.size() == 1) return strs[0]; int c = 0; while(1){ for(int i = 1; i < strs.size(); ++i){ if(strs[i].size() <= c || strs[0].size() <= c || strs[i][c] != strs[0][c]) return strs[0].substr(0, c); } c++; } }
时间: 2024-11-09 21:58:02