码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)

时间:2015-03-03 16:46:23      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:c++   java   leetcode   python   算法   

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


014.Longest_Common_Prefix (Easy)

链接

题目:https://oj.leetcode.com/problems/longest-common-prefix/
代码(github):https://github.com/illuz/leetcode

题意

求多个字符串的最长公共前缀。

分析

一位一位判断即可,没什么坑点。

代码

C++:

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 (i >= strs[j].length() || strs[j][i] != strs[0][i])
					return strs[0].substr(0, i);
		}
		return strs[0];
    }
};


Java:

public class Solution {

    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0)
            return "";
        for (int i = 0; i < strs[0].length(); i++) {
            for (int j = 1; j < strs.length; j++)
                if (strs[j].length() <= i || strs[j].charAt(i) != strs[0].charAt(i))
                    return strs[0].substring(0, i);
        }
        return strs[0];
    }
}


Python:

class Solution:
    # @return a string
    def longestCommonPrefix(self, strs):
        if strs == []:
            return ''
        for i in range(len(strs[0])):
            for str in strs:
                if len(str) <= i or str[i] != strs[0][i]:
                    return strs[0][:i]
        return strs[0]



[LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)

标签:c++   java   leetcode   python   算法   

原文地址:http://blog.csdn.net/hcbbt/article/details/44038897

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