标签:style http color os io ar for div cti
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++; } }
Leetcode 细节实现 Longest Common Prefix
标签:style http color os io ar for div cti
原文地址:http://blog.csdn.net/zhengsenlie/article/details/39137109