题目
地址:https://leetcode-cn.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
代码
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
int minLen = strs[0].length();
for (String str: strs) {
if (str.length() < minLen) {
minLen = str.length();
}
}
for (int i = 0; i < minLen; i++) {
char ch = strs[0].charAt(i);
for (int j = 1; j < strs.length; j++) {
if (ch != strs[j].charAt(i)) {
return strs[0].substring(0, i);
}
}
}
return strs[0].substring(0, minLen);
}
}