leetcode22: longest common prefix

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

 

reminders: 1.

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        // in this question, common prefix means continuious predix substring which is different from the common substring in CLRS.
        // remember this, comfirm it with interviwer before starting to solve problem.
        if( strs.size() ==0) return "";
        if( strs.size() < 2) return strs[0];
        //if( strs[0].size() == 0 ) return ""; this statement is useless, because if the size equeals to 0, it won't go into loop.
        
        char c;
        string rel;
        for( int i=0; i<strs[0].size(); i++) {
            c = strs[0][i];
            for( int j=1; j<strs.size(); j++) {
                if( strs[j][i] != c || strs[j].size() <= i ) {
                    return rel;
                }
            }
            
            rel.push_back( c );
        }
        
        return rel;
    }
};


 

posted @ 2013-01-09 06:29  西施豆腐渣  阅读(160)  评论(0编辑  收藏  举报