LeetCode(14)获取字符串数组中字符串的公共前缀

问题:

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

java解答

class Solution {
    /**
     * 思路
     * 根据这个字符串数组中最短的字符串的长度,确定遍历的次数
     * 在每次遍历中,遍历每个字符串,依次从首个字符串的首个字符开始,分别与每个字符串的对应位置的字符比较
     * 如果不等,则break,如果一次遍历过程结束,没有break,将这个字符放到结果字符串中
     */
    //结果字符串
    private String result = "";
    //字符串数组中最短字符串的长度
    private int minStr = 0;
    //获取这个字符串数组中最短字符串的长度
    public void getMinStr(String[] strs){
        if(strs.length < 1){
            return;
        }
        int temp = strs[0].length();
        for(String str:strs){
            if(temp>str.length()){
                temp = str.length();
            }
        }
        this.minStr = temp;
    }
    //遍历字符串数组,存放结果
    public void getLongestCommonPrefix(String[] strs){
        for(int i = 0;i < this.minStr; i++){
            for(int j = 1; j < strs.length; j++){
                if(strs[0].charAt(i) != strs[j].charAt(i)){
                    return;
                }
            }
            this.result += strs[0].charAt(i);
        }
    }
    public String longestCommonPrefix(String[] strs) {
        if(strs.length < 1){
            return "";
        }else if(strs.length == 1){
            return strs[0];
        }
        this.getMinStr(strs);
        this.getLongestCommonPrefix(strs);
        return this.result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值