longest common prefix

longest common prefix

Brute force way

Iterate for every string, find the result.

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string> &strs) {
 4         int n = strs.size();
 5         if ( 0 == n ) {
 6             return "";
 7         }
 8         string str = strs[0];
 9         int l,j;
10         for ( int i = 1; i < n; i++ ) {
11             l = str.length();
12             j = 0;
13             while ( j < l && str[j] == strs[i][j] ) {
14                 j++;
15             }
16             str = str.substr(0,j);
17         }
18         return str;
19     }
20 };

Loading Disqus comments...
Table of Contents