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

LeetCode---Longest Common Prefix

时间:2015-01-09 09:17:16      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   longest common prefi   

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

Solution:

class Solution 
{
public:
    string longestCommonPrefix(vector<string> &strs) 
    {
        vector<string> s = strs;
        string temp="";
        int n = s.size();
        if(n <= 0)
            return temp;
        temp = s[0];
        int i=1;
        while(i<n)
        {
            temp = longest(s[i],temp);
            i++;
        }
        return temp;
    }
    string longest(const string& s, const string& t)
    {
        string res="";
        int m = s.length();
        int n = t.length();
        n = min(m,n);
        int i=0;
        while(i<n)
        {
            if(s[i] == t[i])
                res += s[i];
            else
                return res;
            i++;
        }
        return res;
        
    }
    int min(int i, int j)
    {
        return i>j? j:i;
    }
};


LeetCode---Longest Common Prefix

标签:leetcode   算法   longest common prefi   

原文地址:http://blog.csdn.net/shaya118/article/details/42536707

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