码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-04-13 23:17:46      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:i++   一个   etc   length   mon   存在   返回   输入   while   

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

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

示例 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

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

标签:i++   一个   etc   length   mon   存在   返回   输入   while   

原文地址:https://www.cnblogs.com/NPC-assange/p/10703411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!