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 "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
找最长前缀公共子串,比较各字符串首字母,如果首字母不同,截取字符串之后的子串继续比较。
substring() 方法返回字符串的子字符串。
public String substring(int beginIndex, int endIndex)
-
beginIndex -- 起始索引(包括), 索引从 0 开始。
-
endIndex -- 结束索引(不包括)。
//java
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String pre = strs[0];
int i = 1;
while(i < strs.length){
while(strs[i].indexOf(pre) != 0)
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}
博客介绍了编写函数查找字符串数组中最长公共前缀的方法。若没有公共前缀则返回空字符串,还提到比较各字符串首字母,若不同则截取子串继续比较,同时介绍了 substring() 方法用于返回子字符串。

被折叠的 条评论
为什么被折叠?



