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

LeetCode记录之14——Longest Common Prefix

时间:2017-09-04 01:03:34      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:color   stringbu   字符串数组   logs   前缀   find   i++   str   tco   

本题虽然是easy难度,题目也一目了然,问题就是在这里,需要考虑的特殊情况太多,太多限制。导致我一点点排坑,浪费了较多时间。

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

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


 

 1 class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         int length =strs.length,strLength=0;
 4         StringBuffer sBuffer=new StringBuffer();
 5         boolean isSame=false;
 6         if(strs.length!=0)//考虑字符串数组可能为空情况
 7             strLength=strs[0].length();
 8         if (strs.length==1) {//考虑字符串数组为一个的情况
 9             return strs[0];
10         }
11         else{
12             for (int i = 0; i < length - 1; i++) {
13                 if (strs[i].length() == 0)//考虑某个字符串为空的情况
14                     return "";
15                 if (strLength > strs[i + 1].length())//求出最短字符串的长度
16                     strLength = strs[i + 1].length();
17 
18             }
19             for (int i = 0; i < strLength; i++) {
20                 for (int j = 0; j < length - 1; j++) {
21                     if (strs[j].charAt(i) == strs[j + 1].charAt(i)) {
22                         isSame = true;
23                     }
24                     else{
25                         isSame=false;
26                     }
27                 }
28                 if (isSame)
29                     sBuffer.append(strs[0].charAt(i));
30                 else
31                     break;
32             }
33             return sBuffer.toString();
34     }
35 }

 

LeetCode记录之14——Longest Common Prefix

标签:color   stringbu   字符串数组   logs   前缀   find   i++   str   tco   

原文地址:http://www.cnblogs.com/vincentme/p/7471809.html

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