[Leetcode 18] 14 Longest Common Prefix

Problem:

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

 

Analysis:

Each time take a character from the first string and compare it with other strings' same position character.

If reaching some end of some string or find a mismatch, then the longest common prefix has been found, just return.

Take some corner cases into considerations([], [""]).

Time Complexity O(n*m), n is the strings in the given input, m is the prefix compared when existing. The worst case for m is length of the shortest string in the array.

Space Complexity O(l), l is the total characters in the String array.

 

Code:

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         if (strs.length == 0 || strs[0].length() == 0)
 6             return "";
 7             
 8         int pos = 0;
 9         char ch = 'c';
10         String s0 = strs[0];
11         while (true) {
12             if (pos == s0.length())
13                 return s0.substring(0, pos);
14             
15             ch = s0.charAt(pos);
16             for (String s : strs) {
17                 if (pos == s.length() || ch!=s.charAt(pos))
18                     return s0.substring(0, pos);
19             }
20             
21             pos += 1;
22         }
23     }
24 }
View Code

 

Attention:

Don't know why in JudgeLarge, sometimes will have Time Limit Exceeded error but sometimes will AC. May be problems in testing environment.

posted on 2013-05-19 03:20  freeneng  阅读(276)  评论(0编辑  收藏  举报

导航