最长公共前缀

参考derrantcm的博客,网址:https://blog.csdn.net/DERRANTCM/article/details/46963385

 

package algorithm;

//最长公共前缀
public class LongestCommonPrefix {
/*
    原题
      Write a function to find the longest common prefix string amongst an array of strings. 
    题目大意
      写一个函数找出一个字串所数组中的最长的公共前缀。 
    解题思路
     第一步先找出长度最小的字符串,然后将这个字符串与其它的字符串相比找出最短的最公共前缀。 
    */
    
    public static String solution(String[] strs){
        
        if(strs==null){
            return "";
        }
        if(strs.length==0){
            return "";
        }
        if(strs.length==1){
            return strs[0];
        }
        
        int arrayLength=strs.length;
        
        int min = Integer.MAX_VALUE;  // 记录最短的字符串的长度
         
        for(int i=0;i<arrayLength;i++){
            int strLength=strs[i].length();
            if(strLength<min){
                min=strLength;
            }
        }
        System.out.println("最短长度为:"+min);
        
        boolean flag=true;
        int i;
        for(i=0;i<min;i++){
            flag=true;
            for(int j=1;j<arrayLength;j++){
               
                if(strs[0].charAt(i)!=strs[j].charAt(i)){ //首先检查所有字符串的第一个字母
                    flag=false;
                    break;
                }
                
            }
            if(flag==false){
                break;
            }
            
        }
        return strs[0].substring(0,i);
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] argss={"abc","abcdef","abckk","abiii"};
        String prefix=solution(argss);
        System.out.println("最长公共前缀="+prefix);
        
    }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值