https://leetcode.com/problems/longest-common-prefix/description/
Write a function to find the longest common prefix string amongst an array of strings.
找出一堆字符串,相同前缀,如:abcdhewuhf,abcjjee,abcd 的最大前缀是abc
一遍过,提交成功--
另外,关于vector的使用,如vector类型strs,想要得到vector类型变量容器中数据个数,用自身函数:strs.capacity()
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(0 == strs.capacity()) return ""; //输入数据量为空的时候,返回空字符串
int n = strs[0].length(); //初始时,最大前缀假设为第一个字符串的长度
string prefix = strs[0];
for( int i = 1; i < strs.capacity(); i++){
if(strs[i].length() < n ) n = strs[i].length(); //某个字符串长度小于最大前缀长度时,改变最大前缀长度
for(int j = 0; j < n; j++){
if(prefix[j] != strs[i][j]){
n = j;
break;
}
}
}
return prefix.substr(0,n);
}
};