leetcode [Longest Common Prefix]

public class Solution {
	public String longestCommonPrefix(String[] strs){
		String res = "";
		boolean flag = true;
		for(int i = 0; flag; i++){
			if(strs.length == 0){
				flag = false;//处理空串的情况
			}
			if(strs.length == 1){//
				flag = false;
				res = strs[0];
			}
			for(int j = 0; j < strs.length - 1; j++){
				if(strs[j].length() <= i || strs[j + 1].length() <= i){//防止下标越界
					flag = false;
					break;
				}
				if(strs[j].charAt(i) != strs[j + 1].charAt(i)){
					flag = false;
					break;
				}
			}
			if(flag){
				res += strs[0].charAt(i);
			}
		}
		return res;
	}
}

解法二(次优解):

public class Solution {
	public String longestCommonPrefix(String[] strs){
		String res = "";
		if(strs.length != 0){//防止下标越界,可以包含长度为1的情况
			Arrays.sort(strs);//巧用排序这个函数,字符串排序是优先按字母,然后长度...的规则
			//按次序比较排序后的第一个字符串与最后一个字符串即可
			String temp1 = strs[0];
			String temp2 = strs[strs.length - 1];
			for(int i = 0; i < temp1.length() && i < temp2.length(); i++){
				if(temp1.charAt(i) == temp2.charAt(i)){
					res += temp1.charAt(i);
				}
				else{
					break;
				}
			}
		}
		return res;
	}
}

解法三(最优解):

public class Solution {
	public String longestCommonPrefix(String[] strs){
		String res = "";
		/*indexOf方法:返回 String对象内第一次出现子字符串的字符位置,
		 * 字符串的IndexOf()方法搜索在该字符串上是否出现了作为参数传递的字符串,
		 * 如果找到字符串,则返回字符的起始位置 (0表示第一个字符,1表示第二个字符依此类推)
		 * 如果说没有找到则返回 -1
		 *注: "".indexof("")的结果为0
		 */
		/*public String substring(int beginIndex, int endIndex)
		 * 从beginIndex开始取,到endIndex结束,从0开始数,其中不包括endIndex位置的字符
		 * 注:string.substring(0,0)的结果为""
		 */
		if(strs.length != 0){//防止下标越界
			res = strs[0];//先找到一个参考值,共同最大的字符串的长度肯定不会超过其中任何一个字符串的长度
			for(int i = 1; i < strs.length; i++){//从参考字符串后的字符串开始
				while(strs[i].indexOf(res) != 0){
					res = res.substring(0, res.length() - 1);//遍历每一个字符串,调整要得的res
					//res.substring(0, res.length() - 1);而不是strs[i].substring(0, res.length() - 1);调整的是res
				}
			}
		}
		return res;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值