题目描述:
Write a function to find the longest common prefix string amongst an array of strings.
https://leetcode.com/problems/longest-common-prefix/description/
思路分析:找出一个string数组中各个元素共有的最长的前缀。我们通过遍历整个数组元素的第一个char、第二个char……来判断每个位置上是否是一致的,如果是一致的就添加到prefix中去并返回它。
代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string prefix = "";
int flag = 0;
if (strs.size() == 0)
return prefix;
else if (strs.size() == 1)
return strs[0];
//special circumstances
for (int i = 0; i< strs[0].length(); i++){//stating form the first char
for (int j = 1; j < strs.size(); j++){//iteration the whole string array
if (strs[0][i] != strs[j][i])
flag = 1;//detecting the chars are not all same
}
if (flag == 1)
break;
prefix+= strs[0][i];//adding chars to prefix
}
return prefix;
}
};
时间复杂度:O(n) //n is the number of elements in strs
反思:一开始很没有头绪,感觉今天脑子糊了。要注意的是数组的大小是用 array.size() 获得的,而字符串的长度则是 string.length(),不要搞混来。另外在leetcode 上有很多奇特的解决方式,诸如二分法、分治法、减法等等,可以学习一发。