leetcode——14longest-common-prefix

leetcode题目链接:https://leetcode.com/problems/longest-common-prefix/description/

python实现

方法一:

class Solution(object):
    def longestCommonPrefix(self, strs):
        lens = len(strs)
        if lens==0:
            return ""
        newstrs = sorted(strs,key=lambda x:len(x))
        if newstrs[0]=="":
            return ""
        if lens==1:
            return strs[0]
        mayprefix = newstrs[0]
        maxprefix = ''
        
        inf = 0 # 作为结束标记,跳出全部循环
        i = 0
        while i<len(mayprefix):
            for j in range(1,lens):
                if newstrs[j][i] != mayprefix[i]:
                    maxprefix = mayprefix[:i] 
                    inf = 1 
                    break        
            if inf ==1:
                break
            maxprefix = mayprefix[:i+1]
            i+=1
        
        return maxprefix
        
strings = ['abc','abc','ab','a','abcd']
a = Solution()
a.longestCommonPrefix(strings)

方法二:

# 方法二:
class Solution(object):
    def longestCommonPrefix(self, strs):
        lens = len(strs)
        if lens==0:
            return ""
        newstrs = sorted(strs,key=lambda x:len(x))
        if newstrs[0]=='':
            return ""
        if lens==1:
            return strs[0]
        
        mayprefix = newstrs[0]
        
        maxprefix = mayprefix #!!在此处进行了改动减少了下面循环中赋值的时间
        
        inf = 0 # 作为结束标记,跳出全部循环
        i = 0
        while i<len(mayprefix):
            for j in range(1,lens):
                if newstrs[j][i] != mayprefix[i]:
                    maxprefix = mayprefix[:i]
                    inf = 1 
                    break        
            if inf ==1:
                break
            i+=1
        
        return maxprefix
    
strings = ['abc','abc','ab','a','abcd']
a = Solution()
a.longestCommonPrefix(strings)

java实现

package test;

public class Leetcode_14 {
	
	public String longestCommonPrefix(String[] strs) {
		if (strs==null || strs.length==0) {
			return "";
		}
		
		String start = strs[0];
		int len;
		for (int i = 0; i < strs.length; i++) {
			len = start.length() > strs[i].length()?strs[i].length():start.length();
			int j;
			for (j = 0; j < len; j++) {
				if (start.charAt(j)!=strs[i].charAt(j)) {
					break;		
				}
			}
			start = start.substring(0, j);
		}

		return start;
	}

	public static void main(String[] args) {
		
		String [] strings = {"ab","ab","abc"};
		Leetcode_14 l= new Leetcode_14();
		String result = l.longestCommonPrefix(strings);
		System.out.println(result);
	}

}

猜你喜欢

转载自blog.csdn.net/u012063773/article/details/79470189
今日推荐