leetcode 14. 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 "".
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.
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
if(strs.length == 1) return strs;
int len = strs.length;
int index = 0;
String result = "";
while(true){
int count = 1;
for(int i = 1; i< len; i++){
if(strs.length() == 0 || strs.length() == 0) return "";
if(index +1 > strs.length() || index +1 > strs.length()) return result;
if(strs.charAt(index) == (strs.charAt(index) )){
count++;
}
else{
return result;
}
if(count == len){
result = result + strs.charAt(index) ;
index++;
}
}
}
}
}
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String cur = strs;
int len = strs.length;
for(int i = 1; i< len; i++){
while(strs.indexOf(cur) != 0){
cur = cur.substring(0, cur.length() -1);
}
}
return cur;
}
}
页:
[1]