Longest Common Prefix

Write a function to find the longest common prefix string among an array of strings.

C++:
01 class Solution {
02 public:
03     string longestCommonPrefix(vector<string> &strs) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         string result;
07         if(strs.size()==0)  return result;
08         for(int i=0;;i++)
09         {
10             if(strs[0].size()<=i)
11             {
12                 return result;
13             }
14             char c=strs[0][i];
15             for(int j=1;j<strs.size();j++)
16             {
17 
18                 if((strs[j].size()<=i)||(strs[j][i]!=c))
19                 {
20                     return result;
21                 }
22             }
23             result+=c;
24         }
25     }
26 };
Advertisements
This entry was posted in Array and linked list, String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s