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

  1. if string length is 0 or string is null, then return "";
  2. initialize prefix = strs[0] ;
  3. traverse the strs[] , and compare the string with the prefix , if the char is the same is prefix, then j++
    • j should be the end index of the prefix
  4. 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;
    }
}