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

LeetCode Longest Common Prefix

时间:2015-01-23 21:38:51      阅读:147      评论: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) {
        if (strs.size() == 0) return "";

        int index = 0;
        for (int i = 0; i < strs.size(); i++) 
            if (strs[i].size() < strs[index].size())
                index = i;

        int ans = strs[index].size();
        for (int i = 0; i < strs.size(); i++) {
            if (i == index) continue;
            int tmp = 0;
            for (int j = 0; j < strs[i].size() && j < ans; j++) {
                if (strs[i][j] == strs[index][j]) 
                    tmp++;
                else break;
            }
            ans = tmp;
        }

        return strs[index].substr(0, ans);
    }
};


LeetCode Longest Common Prefix

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/43061829

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