Leetcode探索——字节跳动·挑战字符串:最长公共前缀

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

如果不存在公共前缀,返回空字符串 ""

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z 。

算法思路:

以pre=strs[0]为参照体,遍历strs(从i=1到strs.length-1),判断是否str[i]以pre为前缀,如否,则pre不断截断最后一个字符,直到str[i]都为以pre为前缀,则为最长前缀。

代码:

 1 class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         
 4         if(strs.length <= 0 ) return "";
 5         if(strs.length == 1 ) return strs[0];
 6         String pre = strs[0];
 7         
 8         for(int i = 1; i < strs.length; i++) {
 9             while(!strs[i].startsWith(pre)) {
10                 pre = pre.substring(0, pre.length() - 1);
11                 if(pre.length() == 0) return "";
12             }
13         }
14         return pre;
15     }
16 }

 

posted @ 2018-12-25 15:30  trashbird_fly  阅读(29)  评论(0)    收藏  举报