Leetcode:编写一个函数来查找字符串数组中最长的公共前缀字符串。

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

思路:设置一个字符串截取窗口(用于截取字符串的前缀),遍历字符串数组,对每个字符串截取一定长度的字符串部分,设置一个标志step,用equals方法比较两两相邻的字符串是否相等,若相等则step++,若step 等于数组长度-1,则表示字符串截取窗口走到了字符串数组末尾元素位置(最后一个字符串元素),然后再一步步增加截取窗口的长度,重复以上操作。

Java代码实现

public class Solution {
      public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0 || strs == null)
            return "";
        if(strs.length == 1)
            return strs[0];
        String prefix = "";
        int len = strs[0].length();
        //找到最短字符串的长度,设置为字符串窗口的最大长度
        for(int i = 1; i < strs.length; i++){
            if(strs[i].length() < len){
                len = strs[i].length();
            }
        }
       //最外层循环表示截取窗口的大小
        for(int i = 0; i < len; i++){
            int step = 0;
        //遍历字符串数组,比较对两两相邻的字符串截取后的字符串进行比较
            for(int j = 0; j < strs.length - 1; j++){
                if(strs[j].substring(0, i+1).equals(strs[j+1].substring(0, i+1))){
                    step++;
                }
            }
         //判断截取窗口是否走到最后
            if(step == strs.length - 1){
                prefix = strs[0].substring(0, i+1);
            }
        }
        return prefix;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值