码迷,mamicode.com
首页 > 其他好文 > 详细

14. Longest Common Prefix

时间:2016-06-22 18:51:52      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
    }
};

=========

题目:找vector中最长公共前缀,

思路:模拟比较的过程,我们可以看到这些.

按照数组中的第一个字符串开始进行比较,

对第一个字符串中的每一个字符,和其他字符串的相应位置进行比较,如果都相同那么将此字符加入到  待返回字符串中.

-------

string longestCommonPrefix(vector<string>& strs) {
        string re;
        if(strs.empty()) return re;
        for(int i = 0;i<(int)strs[0].size();i++){
            for(int j = 0;j<(int)strs.size();j++){
                if(i>=(int)strs[j].size()) return re;
                if(strs[j][i]==strs[0][i])
                    continue;
                else
                    return re;
            }
            re.push_back(strs[0][i]);
        }
        return re;
    }

 

14. Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/li-daphne/p/5608040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!