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

Leetcode题目:Longest Common Prefix

时间:2016-05-10 12:55:25      阅读:134      评论: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) {
        string res;
        int size = strs.size();
        if(size <= 0)
        {
            return res;
        }
        string::iterator sptr[size];
        for(int i = 0;i < size;i++)
        {
            sptr[i] = strs[i].begin();
        }
        bool flag = true;
        while(*(sptr[0]) != ‘\0‘)
        {
            for(int i = 1; i < size;i++)
            {
                if(*(sptr[i]) == *(sptr[i - 1]))
                {
                    continue;
                }
                else
                {
                    flag = false;
                    break;
                }
            }
            if(flag)
            {
                res += *(sptr[0]);
                for(int i = 0;i < size;i++)
                {
                    (sptr[i])++;
                }
            }
            else
            {
                break;
            }
        }
        return res;
    }
};

Leetcode题目:Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/CodingGirl121/p/5477335.html

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