欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

14 最长公共前缀

程序员文章站 2024-02-24 22:51:16
...

效率一般,但浅显易懂 

class Solution {
    public static String longestCommonPrefix(String[] strs) {
        //输入只包含a-z
		if(strs.length==0)return "";
		boolean sign = true;
		int count = strLongestLength(strs);
		int now = 0;
		while(now < count && sign) {
			if(!isCharAtEqual(strs, now)) {sign=false;break;}
			now++;
		}
		return strs[0].substring(0,now);
    }
	//获取字符串数组中最短字符串长度 作为比较次数的最大值
	public static int strLongestLength(String[] strs) {
		int arrayLength = strs.length;
		int count = 0 ;
		int min = 10000;
		while(count < arrayLength) {
			if(strs[count].length() < min) min=strs[count].length();
			count ++;
		}
		return min;
	}
	//遍历字符串数组 判断对应对应字符是否相等
	public static boolean isCharAtEqual(String[] strs , int point) {
		int arrayLength = strs.length;
		int count = 0 ;
		char buffer = strs[count].charAt(point);
		boolean sign = true;
		while(count < arrayLength-1) {
			count++;
			if(!(buffer == strs[count].charAt(point))) sign = false;
		}
		return sign;
	}
}