首页 > 其他 > 详细

Leetcode: Longest Common Prefix

时间:2014-12-09 13:40:59      阅读:231      评论:0      收藏:0      [点我收藏+]

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

分析:这道题没什么好方法,暴力搜索比较即可,在用C++实现时有一个小trick就是"If pos is equal to the string length, the function returns a reference to the null character that follows the last character in the string, which shall not be modified" 所以不必先求出所有string的最小长度。代码如下:

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if(strs.empty()) return "";
        
        for(int i = 0; i < strs[0].length(); i++)
            for(int j = 1; j < strs.size(); j++){
                if(strs[j][i] != strs[0][i]) return strs[0].substr(0,i);
            }
        return strs[0];//strs[0] is the longest common prefix
    }
};

 

Leetcode: Longest Common Prefix

原文:http://www.cnblogs.com/Kai-Xing/p/4152971.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!