【leetcode】14. 最长公共前缀 (JAVA)+ 本地调用测试

在这里插入图片描述

提交

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0){
            return "";
        }
        String ans = strs[0];
        for(int i = 0; i < strs.length; i++){
            int j = 0;
            for(; j < ans.length() && j < strs[i].length(); j++){
                if(ans.charAt(j) != strs[i].charAt(j)){
                    break;
                }
            }
            ans = ans.substring(0, j);
            if(ans.equals(""))
            {
                return ans;
            }
        }
        return ans;
    }    
}

本地调用测试

package leetcode;
//https://leetcode.cn/problems/longest-common-prefix/    14. 最长公共前缀
public class lc_14_longestCommonPrefix {
    public static void main(String[] strs) {
        String[] strst = new String []{"abc", "abcd", "abcde"};
        for(int i = 0; i < strst.length; i++){
            System.out.format("%s ", strst[i]);
        }
//        String ans = longestCommonPrefix(strst); // 静态方法
//        String ans = lc_14_longestCommonPrefix.longestCommonPrefix(strst); //静态方法,直接通过类调用

        // 非静态方法调用,先实例化
        lc_14_longestCommonPrefix arr = new lc_14_longestCommonPrefix(); // 实例化,构造方法会初始化
        String ans = arr.longestCommonPrefix(strst); // 对象调用方法

        System.out.format("\n%s", ans);
    }
//    public static String longestCommonPrefix(String[] strs) { // 静态方法,有关键字static
    public String longestCommonPrefix(String[] strs) { // 非静态方法
        if(strs.length == 0)
            return "";
        String ans = strs[0];
        for(int i =1;i<strs.length;i++) {
            int j=0;
            for(;j<ans.length() && j < strs[i].length();j++) {
                if(ans.charAt(j) != strs[i].charAt(j))
                    break;
            }
            ans = ans.substring(0, j);
            if(ans.equals(""))
                return ans;
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值