Leetcode009--两个字符串的公共前缀


一、原题



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



二、中文



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



三、举例



str1 = “abcmmm”str2 = abchhhh”其公共字符串就是  abc



四、思路



第一步先找出长度最小的字符串,然后将这个字符串与其它的字符串相比找出最短的最公共前缀。 



五、程序



package LeetCode;

public class Leetcode010 {

	private static int longPrefixNum;

	public static void main(String[] args) {
		System.out.println(longestCommonPrefix("abcduuuu", "abcnmwewe"));
	}
	
	/**
	 * @param str1  字符串1
	 * @param str2  字符串2
	 * @return 返回字符串的最长公共前缀
	 */
	public static String longestCommonPrefix(String str1, String str2){
		if(str1 == null || str1.length() < 0 || str2 == null || str2.length() < 0){
			return null;
		}
		int len1 = str1.length();
		int len2 = str2.length();
		longPrefixNum = 0;
		
		if(len1 > len2){
			for(int i = 0; i < len2; i++){
				if(str1.charAt(i) == str2.charAt(i)){
					longPrefixNum++;
				}else{
					break;
				}
			}
		}else{
			for(int i = 0; i < len1; i++){
				if(str1.charAt(i) == str2.charAt(i)){
					longPrefixNum++;
				}else{
					break;
				}
			}
		}
		
		return str1.substring(0, longPrefixNum);
	}

}


--------------------------output--------------------------------


abc



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值