题目描述:
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 "";
int maxlen=Integer.MAX_VALUE;
for(String str:strs){
int len = str.length();
maxlen = maxlen>len? len:maxlen;
}
int common = 0;
boolean goon = true;
//从第一个下标开始遍历
for(int i=0;i<maxlen;i++){
HashMap<String,Integer> hashmap = new HashMap<String,Integer>();
hashmap.put(String.valueOf(strs[0].charAt(i)), 0);
for(int j=1;j<strs.length;j++){
if(!hashmap.containsKey(String.valueOf(strs[j].charAt(i)))){
goon = false;
break;
}
}
if(goon)
common=common+1;
else
break;
}
return strs[0].substring(0,common);
}
}
网友评论