Write a function to find the longest common prefix string amongst an array of strings.
1 class Solution { 2 public: 3 string longestCommonPrefix(vector<string> &strs) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 stringstream rtn; 7 int index = 0; 8 if(strs.size() == 0){ 9 return rtn.str(); 10 } 11 if(strs.size() == 1){ 12 return strs[0]; 13 } 14 while(true){ 15 int i = 0; 16 char ch = strs[i][index]; 17 if(ch != '\0'){ 18 for(; i<strs.size(); i++){ 19 if(ch != strs[i][index]){ 20 return rtn.str(); 21 } 22 } 23 rtn << ch; 24 index++; 25 }else{ 26 return rtn.str(); 27 } 28 } 29 return rtn.str(); 30 } 31 };
Run Status: Accepted!
Program Runtime: 28 milli secs