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

leetcode第14题--Longest Common Prefix

时间:2014-10-16 02:35:11      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

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

就是返回一个字符串数组的所有的公共前缀。不难。我是已第一个字符串为参考,然后依次遍历其他的字符串,一旦遇到不同的。就break。然后返回第一个字符串的相应子序列。

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

 

leetcode第14题--Longest Common Prefix

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/higerzhang/p/4027764.html

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