LeetCode--014--最长公共前缀(java)

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

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

示例 1:

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

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
A:"world" B:"wor" 当A截到只剩下wor时,B.indexOf(A) == 0
 1 class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if(strs==null||strs.length==0)return "";
 4         String res = strs[0];
 5         for(int i = 1;i < strs.length;i++){
 6             while(strs[i].indexOf(res)!=0){
 7                 res = res.substring(0,res.length()-1);
 8             }
 9         }
10         return res;
11     }
12 }

2019-04-13 22:58:35

posted @ 2019-04-13 22:58  Assange  阅读(264)  评论(0编辑  收藏  举报