78 · Longest Common Prefix - LintCode
# Description
Given k
strings, find the longest common prefix (LCP).
# Example
Example 1:
Input:
K strings = ["ABCD", "ABEF", "ACEF"]
Output:
"A"
Explanation:
The longest common prefix is "A".
Example 2:
Input:
K strings = ["ABCDEFG", "ABCEFG", "ABCEFA"]
Output:
"ABC"
Explanation:
The longest common prefix is "ABC".
# Code
- if string length is 0 or string is null, then return "";
- initialize
prefix
=strs[0]
; - traverse the
strs[]
, and compare the string with theprefix
, if the char is the same is prefix, then j++- j should be the end index of the prefix
- if
j==0
meaning that there is one string doesn't have the same prefix as other, you can return "";
public class Solution { | |
public String longestCommonPrefix(String[] strs) { | |
if (strs.length == 0 || strs == null) return ""; | |
String prefix = strs[0]; | |
for (int i = 0; i < strs.length; i++) { | |
int j = 0; | |
while (j < prefix.length() && j < strs[i].length() && strs[i].charAt(j) == prefix.charAt(j)) { | |
j++; | |
} | |
// 只要在 string [] 裡有一個 string 是不同 prefix, 都是錯 | |
if (j == 0) return ""; | |
// 都有一樣的 prefix, 那就取長度 | |
prefix = prefix.substring(0, j); | |
} | |
return prefix; | |
} | |
} |