标签:substring etc math bool false min span i+1 mat
class Solution { public String longestCommonPrefix(String[] strs) { if(strs.length==0) return ""; if(strs.length==1) return strs[0]; int min_len = strs[0].length(); for(int i=1;i<strs.length;i++){ min_len = Math.min(min_len,strs[i].length()); } int index=0; for(;index<min_len;index++){ boolean isPrefix = true; for(int i=0;i<strs.length-1;i++){ if(strs[i].charAt(index)!=strs[i+1].charAt(index)){ isPrefix=false;break; } } if (!isPrefix) {break;} } if(index==0) return ""; else return strs[0].substring(0,index); } }
8ms,47.18%.
结合最快方法改进:
public String longestCommonPrefix(String[] strs) { if(strs==null||strs.length==0) return ""; int min_len = strs[0].length(); for(int i=1;i<strs.length;i++){ min_len = Math.min(min_len,strs[i].length()); } for(int i=0;i<min_len;i++){ char c = strs[0].charAt(i); for(int j=1;j<strs.length;j++){ if(c!=strs[j].charAt(i)) return strs[0].substring(0,i); } } return strs[0].substring(0,min_len); }
有时4ms,99.91%,有时8ms。。可以了。
Leetcode14 Longest Common Prefix
标签:substring etc math bool false min span i+1 mat
原文地址:https://www.cnblogs.com/chason95/p/10016223.html