014 Longest Common Prefix 查找字符串数组中最长的公共前缀字符串

时间:2023-03-09 08:34:11
014 Longest Common Prefix 查找字符串数组中最长的公共前缀字符串

编写一个函数来查找字符串数组中最长的公共前缀字符串。

详见:https://leetcode.com/problems/longest-common-prefix/description/

实现语言:Java

class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null||strs.length==0){
return "";
}
String res=new String();
for(int j=0;j<strs[0].length();++j){
char c=strs[0].charAt(j);
for(int i=1;i<strs.length;++i){
if(j>=strs[i].length()||strs[i].charAt(j)!=c){
return res;
}
}
res+=Character.toString(c);
}
return res;
}
}

参考:https://www.cnblogs.com/grandyang/p/4606926.html