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

Leetcode-Longest Common Prefix

时间:2014-11-29 11:35:58      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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

Solution:

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         String res = "";
 4         if (strs.length==0) return res;
 5         if (strs.length==1) return strs[0];
 6         StringBuilder builder = new StringBuilder();
 7 
 8         for (int i=0;i<strs[0].length();i++){
 9             char cur = strs[0].charAt(i);
10             boolean match = true;
11             for (int j=1;j<strs.length;j++)
12                 if (i>=strs[j].length() || cur!=strs[j].charAt(i)){
13                     match = false;
14                     break;
15                 }
16             if (!match) break;
17             else builder.append(cur);
18         }
19 
20         return builder.toString();
21     }
22 }

 

Leetcode-Longest Common Prefix

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/lishiblog/p/4130223.html

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