LeetCode:Longest Common Prefix

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

 

Solution:题意要求求取字符串数组的最长公共前缀子串。从位置0开始,对每一个位置比较所有的字符串,直到遇到不匹配的字符串位置

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        
        if(strs.empty()) return "";
        
        for(int index=0;index<strs[0].size();index++)
            for(int i=1;i<strs.size();i++)
                if(strs[i][index]!=strs[0][index]) 
                    return strs[0].substr(0,index);
        
        return strs[0];
        
    }
};

 

posted @ 2015-07-11 19:46  尾巴草  阅读(122)  评论(0编辑  收藏  举报