原題連結:http://oj.leetcode.com/problems/longest-common-prefix/
題目描述:
Write a function to find the longest common prefix string amongst an array of strings.
題解:
依然是一道分治法解的題,類似的還有http://www.cnblogs.com/codershell/p/3592992.html
1 class Solution { 2 public: 3 string lcp(string str1,string str2){ 4 int len1 = str1.length(); 5 int len2 = str2.length(); 6 int i,j; 7 for(i=0,j=0; i<len1&&j<len2; i++,j++){ 8 if(str1[i] != str2[j] ) 9 break; 10 } 11 return str1.substr(0,i); 12 } 13 string longestCommonPrefix(vector<string> &strs) { 14 int size = strs.size(); 15 if(size == 0) 16 return ""; 17 if(size == 1) 18 return strs[0]; 19 vector<string> A,B; 20 for(int i=0; i<size/2; i++){ 21 A.push_back(strs[i]); 22 } 23 for(int i=size/2; i<size; i++){ 24 B.push_back(strs[i]); 25 } 26 return lcp(longestCommonPrefix(A),longestCommonPrefix(B)); 27 } 28 };