Tuesday, April 16, 2013

longest common prefix (C++ code)

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才返回成功的。


  1. //find common prefix of two strings  
  2.   
  3. string  findcommon(string first,  string second){  
  4.   
  5.    string res;  
  6.   
  7.    for(int i = 0; i < first.length(); i++){  
  8.   
  9.       if(i >= second.length()) break;  
  10.   
  11.       if(first[i] != second[i]) break;  
  12.   
  13.       else res.push_back(first[i]);  
  14.   
  15.   }  
  16.   
  17.    return res;  
  18.   
  19. }  
  20.   
  21. //main function  
  22.   
  23.  string longestCommonPrefix(vector<string> &strs) {  
  24.   
  25.         string res;  
  26.   
  27.         if(strs.empty()) return res;  
  28.   
  29.        res = strs[0];  
  30.   
  31.         for(int i = 1; i < strs.size(); i++){  
  32.   
  33.            string temp = strs[i];  
  34.   
  35.             res = findcommon(res, temp);  
  36.   
  37.         }  
  38.   
  39.                    
  40.   
  41.       return res;  
  42.   
  43.     }  

1 comment: