Leetcode Longest Common Prefix, Jan 17 '12
Write a function to find the longest common prefix string amongst an array of strings.
Tips: 空字符串不能用NULL返回,新建了一个string才返回成功的。
- //find common prefix of two strings
- string findcommon(string first, string second){
- string res;
- for(int i = 0; i < first.length(); i++){
- if(i >= second.length()) break;
- if(first[i] != second[i]) break;
- else res.push_back(first[i]);
- }
- return res;
- }
- //main function
- string longestCommonPrefix(vector<string> &strs) {
- string res;
- if(strs.empty()) return res;
- res = strs[0];
- for(int i = 1; i < strs.size(); i++){
- string temp = strs[i];
- res = findcommon(res, temp);
- }
- return res;
- }
if (first == "" || second == "")return res;
ReplyDelete