Longest Common Prefix

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

C++:
01 string longestCommonPrefix(vector<string> &strs) {
02        string result;
03        if(strs.size()==0)
04            return result;
05        for(int i=; ; i++){
06           if(i>=strs[0].size())
07               return result;
08           char c=strs[0][i];
09           for(int j=1;j<strs.size();j++){
10               if((strs[j].size()<=i)||(strs[j][i]!=c))
11                   return result;
12           }
13           result+=c;
14       }
15 }
Advertisements
This entry was posted in 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