标签:cas length 快速 common alt 最简 UNC 归类 获得
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 "".
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.
题目归类:
垂直比较
测试用例构建
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null||strs.length==0){
return "";
}
for(int i = 1;i<strs.length;i++){
strs[0]=findPrefix(strs[0],strs[i]);
if(strs[0].length()==0)
return "";
}
return strs[0];
}
public String findPrefix(String a, String b){
if(a.length()==0||b.length()==0)
return "";
int length = a.length()<=b.length()?a.length():b.length();
for(int i = length; i>-1;i--){
if(a.substring(0,i).equals(b.substring(0,i))){
return a.substring(0,i);
}
}
return "";
}
}
leetcode 14. Longest Common Prefix
标签:cas length 快速 common alt 最简 UNC 归类 获得
原文地址:https://www.cnblogs.com/clnsx/p/12321897.html