Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
Rong Xiao committed Nov 6, 2020
1 parent 95e27a7 commit 099dccf
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/main/java/com/example/demo/arraySeries/MaxLengthStr.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.example.demo.arraySeries;

/**
* 最长公共前缀
* 说明:
* 1. 所有输入只包含小写字母 a-z
* 2. 如果不存在公共前缀,则返回""
*/
public class MaxLengthStr {

public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String prefix = strs[0];
int count = strs.length;
for (int i = 1; i < count; i++) {
prefix = longestCommonPrefix(prefix, strs[i]);
if (prefix.length() == 0) {
break;
}
}
return prefix;
}

public static String longestCommonPrefix(String str1, String str2) {
int length = Math.min(str1.length(), str2.length());
int index = 0;
while (index < length && str1.charAt(index) == str2.charAt(index)) {
index++;
}
return str1.substring(0, index);
}

public static String demo(String[] strs){

if(strs == null || strs.length == 0){
return "";
}
String prefix = strs[0];
String outStr = "";
for (int i =0; i<strs.length; i++){
String str = strs[i];
int lengt = Math.min(prefix.length(),strs[i].length());
int index = lengt-1;
while (index < lengt && prefix.charAt(index) == str.charAt(index)){
index++;
}
prefix = prefix.substring(0,index);
}
return prefix;
}
public static void main(String[] args) {

String [] str = {"ddog","dracecar","dcar"};
String outStr = demo(str);
// String outStr = "ddog";
System.out.println("commonPrefix = [" + outStr + "]");

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@

import java.util.*;

/**
* 两个数组的交集
* 说明:
* 1. 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
* 2. 我们可以不考虑输出结果的顺序。
*/
public class TheIntersectionOfTwoNumbers {


Expand Down
1 change: 1 addition & 0 deletions src/main/java/com/example/demo/arraySeries/explain.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# 说明 - 数组系列
1. TheIntersectionOfTwoNumbers - 两个数的交集
2. MaxLengthStr - 最长公共前缀

0 comments on commit 099dccf

Please sign in to comment.