Sunday, May 3, 2015

[Leetcode] Longest Common Prefix

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

Analysis:
Compare each character in first string to all others, return the sub string that is matching all strings.

Solution:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        
     
        string first;
        
        if(strs.size() == 0)
        {
            return first;
        }
        
        first = strs[0];
        
        if(strs.size() == 1)
        {
            return first;
        }
        
        int len = 0;
        bool loop_break = false;
        
        for(int i = 0; i < first.size(); i++)
        {
            for(int j = 1; j < strs.size(); j++)
            {
                if(i < strs[j].size())
                {
                    // find mismatch on ith character, break the loop
                    if(first[i] != strs[j][i])
                    {
                        loop_break = true;
                        break;
                        
                    }

                }
                else
                {
                    // find a string of length that is less than i, break the loop
                    loop_break = true;
                    break;
                }
            }
            
            // no loop break, meaning ith character is matching in all strings
            if(loop_break == false)
              len++;
     
            else
              break;
            
        }
        
        return first.substr(0, len);
        
    }
};

No comments:

Post a Comment