![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/976a86e7f1ba1525f6b4c1a734a783eb.png#pic_center)
第一代:
class Solution {
public String longestCommonPrefix(String[] strs) {
if( strs.length==0 || strs==null){
return "";
}
String firstStr = strs[0];
if( firstStr==""){
return "";
}
String maxSubString = strs[0];
int maxFirstName = firstStr.length();
for( int i=1; i<strs.length; i++ ){
String nextString = strs[i];
if( nextString == "" ){
return "";
}
int j;
for( j=0; j<Math.min(nextString.length(),maxFirstName); j++ ){
if( nextString.charAt(j) != firstStr.charAt(j) ){
break;
}
}
if( j<maxFirstName ){
maxFirstName = j;
maxSubString = firstStr.substring(0,j);
}
}
return maxSubString;
}
}
稍微优化:
class Solution {
public String longestCommonPrefix(String[] strs) {
if( strs.length==0 || strs==null){
return "";
}
String firstString = strs[0];
String maxSubString = strs[0];
for( int i=0; i<strs.length; i++ ){
String nextString = strs[i];
if( nextString == "" ){
return "";
}
String tempSubString = CompareString( nextString, firstString );
if( tempSubString.length()<maxSubString.length() ){
maxSubString = tempSubString;
}
}
return maxSubString;
}
public String CompareString(String nextString, String firstString){
int minLength = Math.min( nextString.length(), firstString.length() );
int j = 0;
while( j<minLength && nextString.charAt(j) == firstString.charAt(j) ){
j++;
}
return nextString.substring( 0,j );
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/793a4cd6774654ed788ad99102d88bbf.png#pic_center)
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode resultHead = new ListNode(-1);
ListNode resultTemp = resultHead;
while( l1!=null && l2!=null ){
if( l1.val <= l2.val ){
resultTemp.next = l1;
l1 = l1.next;
}else{
resultTemp.next = l2;
l2 = l2.next;
}
resultTemp = resultTemp.next;
}
if( l1==null ){
resultTemp.next = l2;
}else{
resultTemp.next = l1;
}
return resultHead.next;
}
}