最长字符串前缀

最长字符串长度

在这里插入图片描述
我的代码如下:

import java.util.*;
public class LongestPrefx {
    
    
	public static void main(String[] args) {
    
    
		//若是在力扣里直接写函数,则还要加上参数传递时,字符数组是否为空的情况;
		String[] str= {
    
    "adou","float","flousjh"};	
		int count=str.length;		
		String special=str[0];			将字符串第一位数赋值
		for(int i=1;i<count;i++) {
    
    
			special=sort(special,str[i]);    //将两个字符串进行比对
										//并将公共字符串赋予第一个字符串
											//与下一个进行查找公共字符串
			if(special.length()==0) {
    
    
				System.out.println(" ");
				break;
				}
		}
		System.out.println(special);
	}
	static String sort(String str1,String str2) {
    
    
		int index=0;
		int min=Math.min(str1.length(), str2.length());
		while(index<min&&str1.charAt(index)==str2.charAt(index)) {
    
      //将字符串从首位一点点进行比对,并且限制条件一定要充分;
			index++;
		}
		return str1.substring(0, index);
	}
}

如有错误,还请斧正。

猜你喜欢

转载自blog.csdn.net/weixin_45956604/article/details/109500211