码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Longest Common Prefix

时间:2016-06-06 01:09:11      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/longest-common-prefix/

题目:

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


算法

[java] view plain copy
 技术分享技术分享
  1. public String longestCommonPrefix(String[] strs) {  
  2.     if (strs.length == 0) {  
  3.         return "";  
  4.     }  
  5.     int miniLength = strs[0].length();  
  6.     for (String s : strs) {  
  7.         if (s.length() < miniLength) {  
  8.             miniLength = s.length();  
  9.         }  
  10.     }  
  11.     for (int j = 0; j < miniLength; j++) {  
  12.         for (int i = 0; i < strs.length; i++) {  
  13.             if (strs[0].charAt(j) != strs[i].charAt(j)) {  
  14.                 return strs[0].substring(0, j);  
  15.             }  
  16.         }  
  17.     }  
  18.     return strs[0].substring(0, miniLength);  
  19. }  

【Leetcode】Longest Common Prefix

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51590935

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