Longest Common Prefix

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

Subscribe to see which companies asked this question.

这个题目的中文意思很简单:
给出一个String数组,求出数组中最长的公共前缀,即所有数组元素开头的最长字符串。

相信一般人看到这个题都会知道解题思路,很简单,这里只说明一点,如果这个最长前缀存在的话,那么它一定也存在于长度最小的字符串中,且遍历这个最小的字符串的时候,最好是从最长也就是整个字符串开始,然后右侧指针左移。
java代码如下:

 if(strs.length==0)  return "";
       if(strs.length==1)  return strs[0];
       String str_temp = strs[0];
       for(int i=0;i<strs.length;i++)
       {
           if(strs[i].length()<str_temp.length()){
               str_temp = strs[i];
           }
       }
       String ans = "";
       for(int i=0;i<str_temp.length();i++){
           String flag = str_temp.substring(0, str_temp.length()-i);
           int count = 0;
           for(int j=0;j<strs.length;j++){
               if(strs[j].startsWith(flag)){
                   count++;
               }
           }
           if(count==strs.length){
               ans = flag ;
               return flag;
           }
       }

       return ans;

代码中设置了一个计数字段,如果以temp开头,则计数加一,循环后,如果结果为数组长度,即所有元素都以此开头,则为最长返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专注网赚的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值