10.3 Longest Common Prefix
10.3.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 14
- Difficulty: Easy
- URL: https://leetcode.com/problems/lc-longest-common-prefix/
- Tags:
- Techniques: Simulation, String
10.3.2 Description
Given an array of strings, return the longest common prefix string among them. If none exists, return "".
10.3.3 Examples
Input: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
10.3.5 Solution - Column Scan
10.3.5.1 Walkthrough
Use the first string as a baseline. For each character index, ensure all other strings have the same character. Stop once a mismatch or end of string occurs.
10.3.5.3 Implementation Steps
- Handle empty input.
- Iterate index
iacross the first string. - For each
i, comparestrs[j].charAt(i)withstrs[0].charAt(i); returnstrs[0].substring(0, i)on mismatch. - If no mismatch, return the entire first string.
10.3.5.4 Code - Java
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
for (int i = 0; i < strs[0].length(); i++) {
char c = strs[0].charAt(i);
for (int j = 1; j < strs.length; j++) {
if (i == strs[j].length() || strs[j].charAt(i) != c) {
return strs[0].substring(0, i);
}
}
}
return strs[0];
}