题解 | #最长公共前缀#

最长公共前缀

http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47



public class Solution {
    /**
     * 
     * @param strs string字符串一维数组 
     * @return string字符串
     */
   public static String longestCommonPrefix (String[] strs) {
       
        int lens=strs.length;
        if(lens==1){
            return strs[0];
        }
        int times=Integer.MAX_VALUE;
        String res=new String();
        for(int index=0;index<lens;index++){
            times=Math.min(times, strs[index].length());
        }
        for(int index=0;index<times;index++){
            if(sign(index, strs)){
                res=res+strs[0].charAt(index);
            }else{
                break;
            }
        }
        return res;
    }
    public static boolean sign(int index,String[] strs){
        int times=0;
        for(int i=0;i<strs.length-1;i++){
            if(strs[i].charAt(index)==strs[i+1].charAt(index)){
                times++;
            }else{
                break;
            }
        }
        if(times==strs.length-1){
            return true;
        }
        return false;
    }
}
全部评论

相关推荐

影04714:把图书管理系统那个项目经验内容适当的减少掉,然后改成据为己有不要说团队项目,因为图书管理系统这类常见的谁来了都能独立写出来,提问能圆过来即可
点赞 评论 收藏
分享
__Offer__:认识的室友啥也不回细节,线下面联想大模型一次通关我给我干不回了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务