LeetCode——Longest Common Prefix

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

写一个函数找出字符串数组中的最长共现前缀字符串。

思路:共现,即要求数组中的所有元素的前缀中都要出现。所以所得的结果肯定是最短字符串的部分或全部或都不是,总之要以最短字符串为基准与其他字符串比较。

	public static String longestCommonPrefix(String[] strs){
		int len = strs.length;
		if(len <= 0)
			return "";
		if(len == 1)
			return strs[0];
		int minlen = strs[0].length();
		String temp = strs[0];
		//找出一个长度最短的字符串
		for(int i=1;i<len;i++){
			if(strs[i].length() < minlen){
				minlen = strs[i].length();
				temp = strs[i];
			}
		}
		int i=0,j = 0;
		StringBuffer buf = new StringBuffer();
		while(j < temp.length()){
			for(i=0;i<strs.length;i++){
				if(strs[i].charAt(j) != temp.charAt(j))
					break;
			}
			if(i < len)
				break;
			buf.append(temp.charAt(j));
			j++;
		}
		return buf.toString();
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值