题目
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 ""
.
分析
1 注意是最长公共前缀,一开始没注意到这个条件浪费了一些时间
2 Java里的两个字符串的匹配函数 indexOf 返回匹配的第一个字符的索引位置
subString 都是很好的用到了
代码
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String res = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(res) != 0){
res = res.substring(0, res.length() - 1);
}
}
return res;
}
}