Saturday, September 21, 2013

Longest Common Prefix

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

This is the simple solution.
  
class Solution {
public:
    string longestCommonPrefix(vector &strs) {
 
         if(strs.size() == 0) return "";

        int num = strs.size();
        int len = strs[0].size();

        for(int j = 0; j            for(int i = 1; i                 if(strs[i][j]!=strs[i-1][j]){
                    return strs[0].substr(0,j);
                }
            }
        }
        return strs[0];    
    }
};


We have a string vector containing different strings. We start off with first letter of string (j=0).
 The other loop starts at i=1 pointing to the string at index 1 in the vector.
The outer loop is for iterating through particular j for all the strings.
In the first iteration of the inner loop i=1, j=0;
strs[1][0] refers to first character of the string at index 1.
strs[0][0] refers to the first character of the string at index 0.
Both of them are compared. If found unequal we return the substring strs[0].substr(0,0) which basically is null here.
In the second iteration of the inner loop i=2, j=0;
strs[2][0] (first character of the string at index 2) is compared with strs[1][0] (first character of string at index 1). Similarly we iterate through all the strings (i) comparing their first characters with the first character of the previous string (i-1).
Then the outer loop is incremented (we compare all strings for their second characters) and proceed so on.
In the worst case the complexity will be O(n2.

No comments:

Post a Comment