Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
Steps:
- Corner check
- Assign strs[0] to String prefix variable
- Get the common prefix of strs[i] and prefix
- Be careful that prefix may be longer than str[i], so need to cut the prefix off if it is longer than strs[i] before element-by-element comparison (otherwise it is easy to have null pointer exception)
// Simplified code
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null) {
return null;
}
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
int j = 0;
while (j < prefix.length() && j < strs[i].length() &&
prefix.charAt(j) == strs[i].charAt(j)) {
j++;
}
if (j == 0) {
return "";
}
prefix = prefix.substring(0, j);
}
return prefix;
}
}
// My own code, can be simplified, use while loop so that you can have multiple conditions
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null) {
return null;
}
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
prefix = getCommonPrefix(prefix, strs[i]);
if (prefix.equals("")) {
break;
}
}
return prefix;
}
public String getCommonPrefix(String prefix, String str) {
// prefix may be longer than str
prefix = (prefix.length() > str.length()) ? prefix.substring(0, str.length()) : prefix;
for (int i = 0; i < prefix.length(); i++) {
if (prefix.charAt(i) != str.charAt(i)) {
prefix = str.substring(0, i);
break;
}
}
return prefix;
}
}