arr[j]) {
+ //这个公式你要品,你细品
+ dp[i] = Math.max(dp[i], dp[j] + 1);
+ }
+ }
+ }
+
+ System.out.println(Arrays.toString(dp));
+
+ int max = 0;
+ int maxIndex = 0;
+ //找到最大值
+ for (int k = dp.length - 1; k >= 0; k--) {
+ if (dp[k] > max) {
+ max = dp[k];
+ maxIndex = k;
+ }
+ }
+
+ System.out.println("max=" + max + "maxIndex=" + maxIndex);
+ System.out.println(arr[maxIndex]);
+ for (int m = maxIndex; m >= 0; m--) {
+ if (arr[m] < arr[maxIndex] && dp[m] == dp[maxIndex] - 1) {
+ maxIndex = m;
+ System.out.println(arr[m]);
+ }
+ }
+ }
+
+ // O N*N; 通过二分查找优化成Ologn
+
+ /**
+ * 通过递增子串的规则,我们发现
+ *
+ * 每次我们都找一个最小
+ *
+ * @param arr
+ */
+ private static void findTwoSplit(int[] arr) {
+ //存储第i个位置结尾,最长递增子串长度
+
+ //根据最后一个dp 值向前遍历,找打小于他的一个值,并且dp[i] = dp[7]-1
+
+ int dp[] = new int[arr.length];
+ //有效值
+ int ends[] = new int[arr.length];
+ ends[0] = arr[0];
+ dp[0] = 1;
+ // 0 right有效区
+ int right = 0;
+ for (int i = 1; i < arr.length; i++) {
+ int l = 0;
+ int r = right;
+ while (l <= r) {
+ int mid = (l + r) / 2;
+ if (arr[i] > ends[mid]) {
+ l = mid + 1;
+ } else {
+ r = mid - 1;
+ }
+ }
+ if (l > right) {//有效区扩张
+ right = l;
+ }
+ ends[l] = arr[i];
+ dp[i] = l + 1;
+
+// for (int j = 0; j < i; j++) {
+// //与前面每一个比较如果大于就比较一下对应dp值是否是最大的赋值给当前
+// if (arr[i] > arr[j]) {
+// //这个公式你要品,你细品
+// dp[i] = Math.max(dp[i], dp[j] + 1);
+// }
+// }
+ }
+
+ System.out.println(Arrays.toString(dp));
+
+ int max = 0;
+ int maxIndex = 0;
+ //找到最大值
+ for (int k = dp.length - 1; k >= 0; k--) {
+ if (dp[k] > max) {
+ max = dp[k];
+ maxIndex = k;
+ }
+ }
+
+ System.out.println("max=" + max + "maxIndex=" + maxIndex);
+ System.out.println(arr[maxIndex]);
+ for (int m = maxIndex; m >= 0; m--) {
+ if (arr[m] < arr[maxIndex] && dp[m] == dp[maxIndex] - 1) {
+ maxIndex = m;
+ System.out.println(arr[m]);
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMaxLongSubSequence.java b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMaxLongSubSequence.java
new file mode 100644
index 0000000..1680018
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMaxLongSubSequence.java
@@ -0,0 +1,78 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.Arrays;
+import java.util.Comparator;
+
+public class DynamicMaxLongSubSequence {
+
+ public static void main(String[] args) {
+
+ String str1 = "1A2C3D4B56";
+
+ String str2 = "B1D23CA45B6A";
+
+
+ String maxLongsubSequence = getMaxLongSubSequence(str1, str2);
+
+ System.out.println(maxLongsubSequence);
+ }
+
+ private static String getMaxLongSubSequence(String str1, String str2) {
+
+
+ char[] charArray1 = str1.toCharArray();
+ char[] charArray2 = str2.toCharArray();
+
+ int[][] dp = new int[str1.length()][str2.length()];
+
+ dp[0][0] = (charArray1[0] == charArray2[0] ? 1 : 0);
+
+ //填充第一行
+ for (int i = 1; i < str1.length(); i++) {
+ int count = (charArray1[i] == charArray2[0] ? 1 : 0);
+ dp[i][0] = Math.max(dp[i - 1][0], count);
+ }
+ //填充第一列
+ for (int j = 1; j < str2.length(); j++) {
+ int count = (charArray1[0] == charArray2[j] ? 1 : 0);
+ dp[0][j] = Math.max(dp[0][j - 1], count);
+ }
+
+ for (int i = 1; i < str1.length(); i++) {
+ for (int j = 1; j < str2.length(); j++) {
+ //去除两边最大值
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
+ if (charArray1[i] == charArray2[j]) {
+ //相等 并不是直接增加1 ,因为前面有可能增加过,所以要和前一行前一列的值+1比较
+ dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + 1);
+ }
+ }
+ }
+
+ int m = str1.length() - 1;
+ int n = str2.length() - 1;
+ //获取子序列
+ char[] res = new char[dp[str1.length() - 1][str2.length() - 1]];
+
+ int index = res.length - 1;
+ while (index >= 0) {
+ if (n > 0 && dp[m][n] == dp[m][n - 1]) {
+ n--;
+ } else if (m > 0 && dp[m][n] == dp[m - 1][n]) {
+ m--;
+ } else {
+ res[index--] = charArray1[m];
+ m--;
+ n--;
+ }
+ }
+ return Arrays.toString(res);
+ }
+
+}
+
+
+
+
+
+
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMaxLongSubString.java b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMaxLongSubString.java
new file mode 100644
index 0000000..b2b8223
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMaxLongSubString.java
@@ -0,0 +1,105 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.Arrays;
+
+public class DynamicMaxLongSubString {
+
+ public static void main(String[] args) {
+
+ String str1 = "1AB2345CD";
+
+ String str2 = "12345EF";
+
+
+ String maxLongsubSequence = getMaxLongSubString(str1, str2);
+
+ System.out.println(maxLongsubSequence);
+ }
+
+ /**
+ * 1 1 1 1 1 1 1
+ * 1 1 1 1 1 1 1
+ * 1 1 1 1 1 1 1
+ * 1 1 1 1 1 1 1
+ * 1 1 2 2 2 2 2
+ * 1 1 2 3 3 3 3
+ * 1 1 2 3 4 4 4
+ * 1 1 2 3 4 4 4
+ * 1 1 2 3 4 4 4
+ * [2, 3, 4, 5]
+ *
+ * @param str1
+ * @param str2
+ * @return
+ */
+ private static String getMaxLongSubString(String str1, String str2) {
+
+
+ char[] charArray1 = str1.toCharArray();
+ char[] charArray2 = str2.toCharArray();
+
+ int[][] dp = new int[str1.length()][str2.length()];
+
+ dp[0][0] = (charArray1[0] == charArray2[0] ? 1 : 0);
+
+ //填充第一行
+ for (int i = 1; i < str1.length(); i++) {
+ int count = (charArray1[i] == charArray2[0] ? 1 : 0);
+ dp[i][0] = Math.max(dp[i - 1][0], count);
+ }
+ //填充第一列
+ for (int j = 1; j < str2.length(); j++) {
+ int count = (charArray1[0] == charArray2[j] ? 1 : 0);
+ dp[0][j] = Math.max(dp[0][j - 1], count);
+ }
+
+ for (int i = 1; i < str1.length(); i++) {
+ for (int j = 1; j < str2.length(); j++) {
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
+ if (charArray1[i] == charArray2[j]
+ && charArray1[i - 1] == charArray2[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ }
+ }
+ }
+ printArray(dp, str1.length(), str2.length());
+ char resultArray[] = new char[dp[str1.length() - 1][str2.length() - 1]];
+ int i = resultArray.length - 1;
+
+
+ for (int j = str1.length() - 1; j > 0; j--) {
+ int a = dp[j][str2.length() - 1];
+ int b = dp[j - 1][str2.length() - 1];
+ if (a > b) {
+ resultArray[i--] = charArray1[j];
+ }
+ if (i == 0 && a <= b) {
+ resultArray[i--] = charArray1[j];
+ }
+ if (i < 0) {
+ break;
+ } else {
+ continue;
+ }
+ }
+
+
+ return Arrays.toString(resultArray);
+ }
+
+
+ private static void printArray(int[][] m, int l1, int l2) {
+ for (int i = 0; i < l1; i++) {
+ for (int j = 0; j < l2; j++) {
+ System.out.print(m[i][j] + " ");
+ }
+ System.out.println();
+ }
+ }
+}
+
+
+
+
+
+
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMoney.java b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMoney.java
new file mode 100644
index 0000000..b093feb
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMoney.java
@@ -0,0 +1,200 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class DynamicMoney {
+
+ public static void main(String[] args) {
+ Integer m[] = new Integer[]{5, 2, 3};
+
+ int mInt[] = new int[]{5, 2, 3};
+ //由大到小排序,效率更高
+ Arrays.sort(m, Collections.reverseOrder());
+
+// int curMoney = 20;//4
+// int curMoney = 19; // 5 5 5 2 2
+ int curMoney = 18; // 5 5 5 3
+
+// int count = splitMoney(m, 0, curMoney);
+ int count = minConins3(mInt, curMoney);
+ System.out.println("count=" + count);
+ }
+
+ /**
+ * 思路就是遍历逐个遍历,使用 0 张 1 ,2 张直到最大
+ *
+ * @param m
+ * @param index
+ * @param curMoney
+ * @return
+ */
+ private static int splitMoney(Integer[] m, int index, int curMoney) {
+ //都遍历完了,也得到了最小值
+ if (curMoney == 0) {
+ return 0;
+ }
+
+ /**
+ * 回溯当前Size
+ */
+ int currentSize = -1;
+ /**
+ * 遍历每一个元素,从不选,到选择最大
+ */
+ for (int i = index; i < m.length; i++) {
+ if (curMoney >= m[i]) {
+ int maxSelect = curMoney / m[i];//最大选择
+ //从0开始 j 就是选择张数
+ for (int j = 0; j <= maxSelect; j++) {
+ int restMoney = curMoney - m[i] * j;
+ int next = splitMoney(m, i + 1, restMoney);
+
+ if (next != -1) {//有解
+ if (currentSize == -1) {
+ //一次没有被回溯直接赋值,这里是i 加一,不是index +1
+ currentSize = j + next;
+ } else {
+ currentSize = Math.min(currentSize, j + next);
+ }
+ } else {
+ if (restMoney == 0) {
+ currentSize = j;
+ }
+ }
+ }
+ }
+ }
+ return currentSize;
+ }
+
+ public int minCoins1(int[] arr, int aim) {
+ if (arr == null || arr.length == 0 || aim < 0) {
+ return -1;
+ }
+ return process(arr, 0, aim);
+ }
+
+ /**
+ * 优化两层循环合并成一层 ,因为循环不是每次都从0开始,后续的遍历不涉及到前面
+ *
+ * @param arr
+ * @param i
+ * @param rest
+ * @return
+ */
+ private int process(int[] arr, int i, int rest) {
+ if (i == arr.length) {
+ return rest == 0 ? 0 : -1;
+ }
+
+ int count = -1;
+
+ for (int k = 0; k * arr[i] <= rest; k++) {
+ int next = process(arr, i + 1, rest - k * arr[i]);
+ if (next != -1) {
+ count = count == -1 ? next + k : Math.min(count, next + k);
+ }
+ }
+ return count;
+ }
+
+
+ /**
+ * 动态规划最优实现方案
+ * @param arr
+ * @param aim
+ * @return
+ */
+ public static int minConins2(int[] arr, int aim) {
+ if (arr == null || arr.length == 0 || aim < 0) {
+ return -1;
+ }
+ int N = arr.length;
+ int[][] dp = new int[N + 1][aim + 1];
+ //设置最后一排的值,除dp[N][0]外,其他都是-1
+
+ for (int col = 1; col <= aim; col++) {
+ dp[N][col] = -1;
+ }
+ for (int i = N - 1; i >= 0; i--) {//从底向上计算每一行
+ for (int rest = 0; rest <= aim; rest++) {
+ dp[i][rest] = -1;//初始时先设置dp[i][rest]的值无效
+ if (dp[i + 1][rest] != -1) {//下面的值如果有效
+ dp[i][rest] = dp[i + 1][rest];//先设置成下面的值
+ }
+ if (rest - arr[i] >= 0 && dp[i][rest - arr[i]] != -1) {
+ if (dp[i][rest] == -1) {
+ dp[i][rest] = dp[i][rest - arr[i]] + 1;
+ } else {
+ dp[i][rest] = Math.min(dp[i][rest], dp[i][rest - arr[i]] + 1);
+ }
+ }
+ }
+
+ }
+ printArray(dp);
+ return dp[0][aim];
+ }
+
+ /**
+ * 动态规划普通方案
+ * @param arr
+ * @param aim
+ * @return
+ */
+ public static int minConins3(int[] arr, int aim) {
+ if (arr == null || arr.length == 0 || aim < 0) {
+ return -1;
+ }
+ int N = arr.length;
+ int[][] dp = new int[N + 1][aim + 1];
+ //设置最后一排的值,除dp[N][0]外,其他都是-1
+
+ //最后一排为溢出所以都为-1无解
+ for (int col = 1; col <= aim; col++) {
+ dp[N][col] = -1;
+ }
+ for (int i = N - 1; i >= 0; i--) {//从底向上计算每一行
+ for (int rest = 0; rest <= aim; rest++) {
+ singleDataCalculate(arr[i], dp, i, rest);
+ }
+ }
+ printArray(dp);//测试打印
+ return dp[0][aim];
+ }
+
+ //这个可以优化
+ //把所有等式列出来发现 dp[i][rest] = Math.min(dp[i][rest], dp[i][rest - arr[i]] + 1);
+ private static void singleDataCalculate(int i, int[][] dp, int i2, int rest) {
+ dp[i2][rest] = -1;//初始时先设置dp[i][rest]的值无效
+ int k = rest / i2;//可试的最大张数
+ if (rest == 0) {//如果0表示不需要找钱 也就需要0张
+ dp[i2][rest] = 0;
+ } else {
+ int minValue = -1;//记录最小值
+ for (int j = 0; j <= k; j++) {
+ int next = dp[i2 + 1][rest - j * i2];
+ if (next != -1) {//-1表示无解不记录统计
+ if (minValue == -1) {//第一次统计,无需比较直接赋值
+ minValue = next + j;
+ } else {
+ minValue = Math.min(minValue, next + j);
+ }
+ }
+ }
+ dp[i2][rest] = minValue;
+ }
+ }
+
+ private static void printArray(int[][] m) {
+ for (int i = 0; i < 4; i++) {
+ for (int j = 0; j < 19; j++) {
+ System.out.print(m[i][j] + " ");
+ }
+ System.out.println();
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMoneyWays.java b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMoneyWays.java
new file mode 100644
index 0000000..3137f73
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicMoneyWays.java
@@ -0,0 +1,100 @@
+package com.wangpos.datastructure.algorithm;
+
+public class DynamicMoneyWays {
+
+ public static void main(String[] args) {
+
+ int arr[] = new int[]{5, 1};
+
+ int aim = 15;
+ /***
+ * 5
+ * 55
+ * 555
+ * 11111111
+ *
+ * 10 5
+ * 10 1 1 1 1 1
+ *
+ */
+// int aim = 1000;
+
+// int result = coin(arr, 0, aim);
+ int result = coin2(arr, aim);
+ System.out.println(result);
+ }
+
+ private static int coin(int[] arr, int index, int aim) {
+ if (index == arr.length) {
+ return 0;
+ }
+ int count = 0;
+ int maxUse = 0;
+ //找到小于当前面值的元素
+ for (int i = index; i < arr.length; i++) {
+ maxUse = aim / arr[i];
+ if (maxUse != 0) {
+ index = i;
+ break;
+ }
+ }
+
+ if (maxUse != 0) {//表示没有越界
+ for (int j = 0; j <= maxUse; j++) {
+ int rest = aim - j * arr[index];
+ if (rest == 0) {//有解
+ count += 1;
+ } else {//无解,遍历下一个
+ int next = coin(arr, index + 1, rest);
+ if (next != 0) {//等于0无解
+ count += next;
+ }
+ }
+ }
+ }
+ return count;
+ }
+
+ /**
+ * 动态规划方法
+ * @param arr
+ * @param aim
+ * @return
+ */
+ private static int coin2(int[] arr, int aim) {
+ int dp[][] = new int[arr.length + 1][aim + 1];
+ for (int i = 0; i <= arr.length; i++) {
+ dp[i][0] = 1;
+ }
+
+ int N = arr.length - 1;
+ for (int i = N; i >= 0; i--) {
+ for (int j = 1; j <= aim; j++) {
+ int maxValue = j / arr[i];
+ if (maxValue == 0) {
+ continue;//无效
+ }
+ int count = 0;
+ for (int k = 0; k <= maxValue; k++) {
+ int before = dp[i + 1][j - k * arr[i]];
+ count += before;
+ }
+ dp[i][j] = count;
+
+ }
+ }
+
+ printArray(dp);
+ return dp[0][aim];
+ }
+
+
+ private static void printArray(int[][] m) {
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 16; j++) {
+ System.out.print(m[i][j] + " ");
+ }
+ System.out.println();
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicNestLetter.java b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicNestLetter.java
new file mode 100644
index 0000000..e68f0f9
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicNestLetter.java
@@ -0,0 +1,92 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.Arrays;
+import java.util.Comparator;
+
+public class DynamicNestLetter {
+
+ public static void main(String[] args) {
+ int arr[][] = new int[][]{{3, 4}, {2, 3}, {4, 5}, {1, 3}, {2, 2}, {3, 6}, {1, 2}, {3, 2}, {2, 4}};
+ // int arr[][] = new int[][]{{3, 4}, {2, 3}, {4, 5}, {1, 3}, {2, 2}, {3, 6}};
+
+ int result = calculateTwoSplit(getSortedEnvelopes(arr));
+ System.out.println(result);
+ }
+
+ /**
+ * 将数组按照按照长度排序,然后求宽度的最长增长子串
+ *
+ * 。为什么呢?这与我们的排序策略有关,按照长度从小到大排序,长度相等的信封之间按照宽度从大到小排序。
+ *
+ * @param arr
+ * @return
+ */
+ private static int calculateTwoSplit(Envelope[] arr) {
+
+ //存储第i个位置结尾,最长递增子串长度
+
+ //根据最后一个dp 值向前遍历,找打小于他的一个值,并且dp[i] = dp[7]-1
+
+ int dp[] = new int[arr.length];
+ //有效值
+ int ends[] = new int[arr.length];
+ ends[0] = arr[0].wid;
+ dp[0] = 1;
+ // 0 right有效区
+ int right = 0;
+ for (int i = 1; i < arr.length; i++) {
+ int l = 0;
+ int r = right;
+ while (l <= r) {
+ int mid = (l + r) / 2;
+ if (arr[i].wid > ends[mid]) {
+ l = mid + 1;
+ } else {
+ r = mid - 1;
+ }
+ }
+ if (l > right) {//有效区扩张
+ right = l;
+ }
+ ends[l] = arr[i].wid;
+ dp[i] = l + 1;
+
+ }
+
+ return right + 1;
+
+ }
+
+ //这个排序数组,我们长度是按小到大,所以只需要看宽度的递增子序列即可
+ public static Envelope[] getSortedEnvelopes(int[][] matrix) {
+ Envelope[] res = new Envelope[matrix.length];
+ for (int i = 0; i < matrix.length; i++) {
+ res[i] = new Envelope(matrix[i][0], matrix[i][1]);
+ }
+ Arrays.sort(res, new EnvelopeComparator());
+ return res;
+ }
+
+}
+
+class Envelope {
+ public int len;
+ public int wid;
+
+ public Envelope(int weight, int hight) {
+ len = weight;
+ wid = hight;
+ }
+}
+
+class EnvelopeComparator implements Comparator {
+ @Override
+ public int compare(Envelope o1, Envelope o2) {
+ return o1.len != o2.len ? o1.len - o2.len : o2.wid - o1.wid;
+ }
+}
+
+
+
+
+
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicProgram.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicProgram.kt
new file mode 100644
index 0000000..b25a663
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicProgram.kt
@@ -0,0 +1,145 @@
+package com.wangpos.datastructure.algorithm
+
+import android.os.Build.VERSION_CODES.N
+import kotlin.math.max
+import android.icu.lang.UCharacter.GraphemeClusterBreak.V
+
+
+/**
+ * 动态规划算法,是解决多阶段决策问题常用的最优化理论
+ *
+ *
+ * 1. 定义最优子问题
+ *
+ * 2. 定义状态
+ *
+ * 3. 定义决策和状态转换方程
+ *
+ * 4. 确定边界条件
+ *
+ * 01 背包问题,用动态规划法
+ *
+ * 给定 n 种物品和一个容量为 C 的背包,物品 i 的重量是 wi,其价值为 vi 。
+ *
+ * 应该如何选择装入背包的物品,使得装入背包中的物品的总价值最大?
+ *
+ * 分析一波,面对每个物品,我们只有选择拿取或者不拿两种选择,不能选择装入某物品的一部分,也不能装入同一物品多次。
+ *
+ * 声明一个 大小为 m[n][c] 的二维数组,m[ i ][ j ] 表示 在面对第 i 件物品,且背包容量为 j 时所能获得的最大价值
+ *
+ * 那么我们可以很容易分析得出 m[i][j] 的计算方法,
+ *
+ * 1). j < w[i] 的情况,这时候背包容量不足以放下第 i 件物品,只能选择不拿 所以价值还是和上次,只不过容量变大了,但也是当前背包容量的最大值
+ * (这个当前容量最大值得意思,只对当前放的这个些物品来讲,比如后面有价值更大的,我们不在本次考虑范围,本次考虑就是放当前物品时背包的最大价值,
+ * 同理,当放入第二件物品时,我们就考虑两件物品时当前背包的最大值,我们会一次把所有情况,按照放入物品数量的增加,和背包容量的增加,一次获取最大价值
+ * )
+ * m[ i ][ j ] = m[ i-1 ][ j ] (m[i-1][j]表示容量增加了,但是不拿物品的价值,对应表正的上一行数据,也是之前算好了)
+ *
+ *
+ * 2). j>=w[i] 的情况,这时背包容量可以放下第 i 件物品,我们就要考虑拿这件物品是否能获取更大的价值。
+
+如果拿取,m[ i ][ j ]= m[ i-1 ][ j-w[ i ] ] + v[ i ]。
+
+注意这里解释一下,当前物品数量和背包容量对应的最大值 = 没放入该物品前数量和没放入物品前的容量的最大值 + 当前物品价值
+
+(所以没放入物品前数量对应i-1,
+而容量对应j-w[i],就是当前可以容纳容量j减去当前要放入物品的容量,二对一这个值,在前面的求解当中已经求解,所以,我们就能推倒新的解 )
+
+这里的m[ i-1 ][ j-w[ i ] ]指的就是考虑了i-1件物品,背包容量为j-w[i]时的最大价值,也是相当于为第i件物品腾出了w[i]的空间。
+
+如果不拿,m[ i ][ j ] = m[ i-1 ][ j ]
+
+究竟是拿还是不拿,自然是比较这两种情况那种价值最大。
+
+注意,当我们拿第二件物品的时候,通过这个算法是存在替换的第一件物品的情况,之前一直不理解,以为很顺序有关,第一件放进去了,就一直在里面,后面的累加,实际不是这样
+
+m[ i-1 ][ j-w[ i ] ] 就是会根据当前容量去寻找没装前的容量的最大值 然后再加上自身的价值在去进行补缴
+
+ *
+ *
+ *
+ * 价值数组v = {8, 10, 6, 3, 7, 2},
+
+重量数组w = {4, 6, 2, 2, 5, 1},
+
+背包容量C = 12 时对应的m[i][j]数组
+
+ */
+
+/**
+ * 注意,我们再数组前添加一个零,这样我们就可以从第一个处理了,第一个处理的实际是第二个数据
+ */
+fun main(arg: Array) {
+ var N = 15
+
+ var v = arrayOf(0, 8, 10, 6, 3, 7, 2)
+ var w = arrayOf(0, 4, 6, 2, 2, 5, 1)
+
+ var n = 7
+ var c = 13
+
+ var m = Array(7) { IntArray(13) }
+
+ dynamicBag(w, v, n, c, m)
+
+ // 1 2 3
+
+}
+
+/**
+ * k) 到此,01背包问题已经解决,利用动态规划解决此问题的效率即是填写此张表的效率,
+ * 所以动态规划的时间效率为O(number*capacity)=O(n*c),由于用到二维数组存储子问题的解,所以动态规划的空间效率为O(n*c);
+ */
+
+fun dynamicBag(w: Array, v: Array, n: Int, c: Int, m: Array) {
+
+ for (i in 1 until n) {
+ for (j in 1 until c) {
+ if (j >= w[i]) {
+ m[i][j] = max(m[i - 1][j], m[i - 1][j - w[i]] + v[i])
+ } else {
+ m[i][j] = m[i - 1][j];
+ }
+ }
+ }
+
+
+ for (i in 1 until n) {
+ for (j in 1 until c) {
+ print(" ${m[i][j]} ")
+ }
+ println()
+ }
+
+ var x = arrayOf(0, 0, 0, 0, 0, 0, 0)
+
+ println("查找哪些放入背包了")
+ findData(x, w, v, n - 1, c - 1, m)
+
+ for (i in 0 until x.size) {
+ if (x[i] == 1) {
+ println(i)
+ }
+ }
+}
+
+/**
+ * 另起一个 x[ ] 数组,x[i]=0表示不拿,x[i]=1表示拿。
+
+m[n][c]为最优值,如果m[n][c]=m[n-1][c] ,说明有没有第n件物品都一样,则x[n]=0 ;
+否则 x[n]=1。当x[n]=0时,由x[n-1][c]继续构造最优解;
+当x[n]=1时,则由x[n-1][c-w[i]]继续构造最优解。以此类推,可构造出所有的最优解。
+ *
+ */
+
+fun findData(x: Array, w: Array, v: Array, n: Int, c: Int, m: Array) {
+ if (n >= 1) {
+ if (m[n][c] == m[n - 1][c]) {
+ x[n] = 0
+ findData(x, w, v, n - 1, c, m)
+ } else if (c - w[n] >= 0 && m[n][c] == m[n - 1][c - w[n]] + v[n]) {
+ x[n] = 1
+ findData(x, w, v, n - 1, c - w[n], m)
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicProgramWorkStastion.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicProgramWorkStastion.kt
new file mode 100644
index 0000000..64dea25
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicProgramWorkStastion.kt
@@ -0,0 +1,52 @@
+package com.wangpos.datastructure.algorithm
+
+
+/**
+ * 动态规划首先确定子问题,也就是决策问题
+ */
+fun main(arg: Array) {
+
+ // 第一条线装配站
+ var station1 = arrayOf(1, 10, 6, 3, 7, 2)
+ // 第二条线装配站
+ var station2 = arrayOf(4, 6, 2, 2, 5, 1)
+
+ var time = Array(6) { IntArray(2) }
+
+ dynamic(station1, station2, time)
+
+}
+
+fun dynamic(station1: Array, station2: Array, time: Array) {
+ for (i in 0..5) {
+ if (station1[i] < station2[i]) {
+ time[i][0] = station1[i]
+ } else {
+ time[i][1] = station2[i]
+ }
+ }
+
+ findSmallTimes(time)
+}
+
+fun findSmallTimes(time: Array) {
+ time.forEach {
+ if (it[0] > 0) {
+ println("one ${it[0]}")
+ } else {
+ println("two ${it[1]}")
+ }
+ }
+
+}
+
+
+
+/**
+用动态规划法设计算法的关键是找出子问题和子问题状态的定义。
+子问题的状态就是子问题的最优解,当子问题的规模是最终的问题的时候,
+那么其对应的状态就是问题的最优解。基于这一思想,通常选择把问题的规模作为状态变量的方式定义子问题。
+以取硬币问题为例,其问题是取 N 元硬币需要的最小硬币数量。
+于是我们就选择“取 i(0 ≤ i ≤ N)元硬币需要的最小硬币数量”作为子问题,
+并定义状态 d[i] 为取 i 元硬币需要的最小硬币数量。
+ */
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicRobert.java b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicRobert.java
new file mode 100644
index 0000000..9999c2d
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicRobert.java
@@ -0,0 +1,81 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class DynamicRobert {
+
+ private static int N = 7;
+ private static int K = 10;//这里步骤要+1
+ private static int P = 4;//这里数组-1
+
+ public static void main(String[] args) {
+
+ int dp[][] = new int[K][N];
+
+ int result = way(dp);
+
+ System.out.println("result="+result);
+
+ printArray(dp);
+ }
+
+ private static int way(int[][] dp) {
+ dp[0][P] = 1;
+ for (int i = 1; i < K; i++) {
+ dp[i][0] = dp[i][0] + dp[i - 1][1];
+ dp[i][N - 1] = dp[i][N - 1] + dp[i - 1][N - 2];
+ for (int j = 1; j < N - 1; j++) {
+ dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1];
+ }
+ }
+
+ return dp[9][3];
+ }
+
+
+ private static void printArray(int[][] m) {
+ for (int i = 0; i < K; i++) {
+ for (int j = 0; j < N; j++) {
+ System.out.print(m[i][j] + " ");
+ }
+ System.out.println();
+ }
+
+ }
+
+ public int ways1(int N, int M, int K, int P) {
+ if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
+ return 0;
+ }
+ return walk(N, M, K, P);
+ }
+
+
+ /**
+ * @param N 位置1~N
+ * @param cur 当前位置 可变参数
+ * @param rest 剩余步骤 可变参数
+ * @param P 最终目标位置P
+ * @return 表示解法数量
+ */
+ public int walk(int N, int cur, int rest, int P) {
+
+ if (rest == 0) {
+ return cur == P ? 1 : 0;
+ }
+
+ if (cur == 1) {
+ return walk(N, 2, rest - 1, P);
+ }
+
+ if (cur == N) {
+ return walk(N, N - 1, rest - 1, P);
+ }
+
+ return walk(N, cur + 1, rest - 1, P) + walk(N, cur - 1, rest - 1, P);
+ }
+
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicShootBalloon.java b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicShootBalloon.java
new file mode 100644
index 0000000..f600b7b
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/DynamicShootBalloon.java
@@ -0,0 +1,33 @@
+package com.wangpos.datastructure.algorithm;
+
+public class DynamicShootBalloon {
+
+ public static void main(String[] args) {
+
+ int[] arr = new int[]{3, 2, 5};
+
+// int result = shoot(arr, 0, 1);
+
+
+ }
+
+// private static int shoot(int[] arr, int l, int r) {
+//
+// int score = 0;
+// if (l >= 0) {
+// int cv = arr[l];
+// int lv = 1;
+// int rv = 1;
+// if (l - 1 >= 0) {
+// lv = arr[l - 1];
+// }
+// if (r < arr.length) {
+// rv = arr[r];
+// }
+// score = lv * cv * rv;
+// }
+//
+//
+// return 0
+// }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/Greedy.java b/app/src/main/java/com/wangpos/datastructure/algorithm/Greedy.java
new file mode 100644
index 0000000..fc69d35
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/Greedy.java
@@ -0,0 +1,128 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * 找零是一个很常见的问题,平时找钱为了都会考虑尽可能找少的数量的钱给用户,顾客也不希望自己得很多零钱
+ * 这是一个典型的使用贪婪算法的题
+ *
+ * 通过币种的问题我们发现,贪心算法每次都要求选择最优的,所以,最终结果并不一定是最优解,
+ *
+ * 硬币种类
+ * [[25, 20, 10, 5, 1]]
+ * 应找给对方的硬币 数量 :4
+ * [[25, 10, 5, 1]]
+ *
+ *
+ * 硬币种类
+ * [[25, 20, 5, 1]]
+ * 应找给对方的硬币 数量 :5
+ * [[25, 5, 5, 5, 1]] 实际最优 是 20 20 1
+ *
+ * 实际顾客需要的是20 20 1 还是 25 5 5 5 1呢,答案是第二个,因为他心理更想留大面值币种
+ *
+ *
+ * 实际场景 顾客 希望的是尽量给我整意思就是 最大的面值的钱先给我找,也就是贪心算法
+ *
+ * 贪心算法效率高,找钱就是需要效率高的场景,但影响最终找的金额数,所以
+ *
+ * 贪心算法可以作为其他最优解算法中的辅助算法
+ */
+public class Greedy {
+ static List coins = new ArrayList();
+
+ public static void main(String[] args) {
+ // 币种是 25 20 10 5 1
+// coins.add(25);
+// coins.add(20);
+// coins.add(10);
+// coins.add(5);
+// coins.add(1);
+
+ // 币种是 25 20 5 1
+ coins.add(25);
+ coins.add(20);
+ coins.add(5);
+ coins.add(1);
+
+ System.out.println("硬币种类");
+ System.out.println(Arrays.asList(coins));
+
+ int target = 41;
+ Result result = getLeastCoins(target);
+ System.out.println("应找给对方的硬币 数量 :" + result.datas.size());
+ System.out.println(Arrays.asList(getLeastCoins(target).datas));
+
+ System.out.println(Arrays.asList(getLeastNumberCoins(target).datas));
+ }
+
+ private static Result getLeastCoins(int target) {
+ Result result = new Result();
+ result.datas = new ArrayList<>();
+ //已知coins是有序的
+ for (Integer coin : coins) {
+ if (target >= coin) {
+ // 求个数
+ int count = target / coin;
+ for (int i = 0; i < count; i++) {
+ result.datas.add(coin);
+ }
+ // 取余数
+ target = target % coin;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * 可以采用局部最优解法加排序算法,找到最优解
+ * @param target
+ * @return
+ */
+
+ private static Result getLeastNumberCoins(int target) {
+ Result minNumberResult = new Result();
+
+ for (int i = 0; i < coins.size(); i++) {
+ Result current = getLeastCoinsByList(i, target);
+ if (minNumberResult.datas != null) {
+ if (minNumberResult.getCount() > current.getCount()) {
+ minNumberResult.datas = current.datas;
+ }else{
+ minNumberResult.datas = current.datas;
+ }
+ }
+ }
+
+ return minNumberResult;
+ }
+
+ private static Result getLeastCoinsByList(int i, int target) {
+ Result result = new Result();
+ result.datas = new ArrayList<>();
+ //已知coins是有序的
+ for (int j = i; j < coins.size(); j++) {
+ int coin = coins.get(i);
+ if (target >= coin) {
+ // 求个数
+ int count = target / coin;
+ for (int m = 0; m < count; m++) {
+ result.datas.add(coin);
+ }
+ // 取余数
+ target = target % coin;
+ }
+ }
+ return result;
+ }
+
+ static class Result {
+ public List datas = null;
+
+ public int getCount() {
+ return datas.size();
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/Greedy01Bag.java b/app/src/main/java/com/wangpos/datastructure/algorithm/Greedy01Bag.java
new file mode 100644
index 0000000..76b66e8
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/Greedy01Bag.java
@@ -0,0 +1,179 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+
+/**
+ * 贪心算法求解01 背包问题
+ *
+ * 假设背包最多承载的重量是150 ,不考虑体积的情况
+ *
+ * 现在有 重量 wi = [ 35,30,60,50,40,10,25] 7个物品
+ * 价值 pi = [10,40,30,50,35,40,30]
+ *
+ *
+ * 按价值贪婪算法
+ * 总重量=130
+ * 总价值=165
+ *
+ * 按最轻贪婪算法
+ * 总重量=140
+ * 总价值=155
+ *
+ * 按价值密度贪婪算法
+ * 总重量=150
+ * 总价值=170
+ *
+ *
+ * 最终都得不到最优解,最优解需要动态规划法来解决
+ */
+
+
+public class Greedy01Bag {
+
+ public static void main(String[] args) {
+
+ // 确定子问题
+
+ // 贪婪策略有3种,
+ // 第一种给句物品价值选择,每次都选择价值最高的物品
+
+ int[] pi = {10, 40, 30, 50, 35, 40, 30};
+ List things = new ArrayList<>();
+ things.add(new Thing(35, 10, 0));
+ things.add(new Thing(30, 40, 0));
+ things.add(new Thing(60, 30, 0));
+ things.add(new Thing(50, 50, 0));
+ things.add(new Thing(40, 35, 0));
+ things.add(new Thing(10, 40, 0));
+ things.add(new Thing(25, 30, 0));
+
+ Bag bag = getMAX(things);
+ System.out.println("按价值使用贪婪算法");
+ System.out.println(Arrays.asList(bag.datas));
+
+ System.out.println("总重量=" + bag.getTotalWeight());
+ System.out.println("总价值=" + bag.getTotalValue());
+ }
+
+
+ private static Bag getMAX(List things) {
+ Bag bag = new Bag(150);
+ bag.datas = new ArrayList<>();
+ for (int i = 0; i < things.size(); i++) {
+// Thing thing = getMaxValueThing(things);
+// Thing thing = getMinWeightThing(things);
+ Thing thing = getMaxValueDensity(things);
+ if (thing != null && thing.status == 0) {
+ if (bag.weight >= thing.weight) {
+ thing.status = 1;
+ bag.datas.add(thing);
+ bag.weight = bag.weight - thing.weight;
+ } else {
+ thing.status = 2;
+ }
+ }
+ }
+
+ return bag;
+ }
+
+ // 第一种给句物品价值选择,每次都选择价值最高的物品
+ private static Thing getMaxValueThing(List things) {
+ Thing maxThing = null;
+ for (Thing thing : things) {
+ if (thing.status == 0) {
+ if (maxThing == null) {
+ maxThing = thing;
+ } else if (maxThing.value < thing.value) {
+ maxThing = thing;
+ }
+ }
+ }
+ return maxThing;
+ }
+
+ // 第二种给句物品价值选择,每次都选择最轻物品
+ private static Thing getMinWeightThing(List things) {
+ Thing maxThing = null;
+ for (Thing thing : things) {
+ if (thing.status == 0) {
+ if (maxThing == null) {
+ maxThing = thing;
+ } else if (maxThing.weight > thing.weight) {
+ maxThing = thing;
+ }
+ }
+ }
+ return maxThing;
+ }
+
+ // 第三种给句物品价值选择,每次都价值密度大的
+ private static Thing getMaxValueDensity(List things) {
+ Thing maxThing = null;
+ for (Thing thing : things) {
+ if (thing.status == 0) {
+ if (maxThing == null) {
+ maxThing = thing;
+ } else if ((maxThing.value*1f / maxThing.weight) < (thing.value*1f / thing.weight)) {
+ maxThing = thing;
+ }
+ }
+ }
+ return maxThing;
+ }
+
+
+ static class Bag {
+ public Bag(int weight) {
+ this.weight = weight;
+ }
+
+ List datas;
+ int weight;
+
+ public int getTotalWeight() {
+ int totalW = 0;
+ for (Thing data : datas) {
+ totalW = totalW + data.weight;
+ }
+ return totalW;
+ }
+
+ public int getTotalValue() {
+
+ int totalV = 0;
+ for (Thing data : datas) {
+ totalV = totalV + data.value;
+ }
+ return totalV;
+ }
+ }
+
+ static class Thing {
+ @Override
+ public String toString() {
+ return "Thing{" +
+ "weight=" + weight +
+ ", value=" + value +
+ ", status=" + status +
+ '}';
+ }
+
+ public Thing(int weiget, int value, int status) {
+ this.weight = weiget;
+ this.value = value;
+ this.status = status;
+ }
+
+ int weight;
+ int value;
+ int status;// 0未选中,1选中,2不合适
+
+ }
+
+}
+
+
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/IterationGCD.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/IterationGCD.kt
new file mode 100644
index 0000000..c293f52
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/IterationGCD.kt
@@ -0,0 +1,76 @@
+package com.wangpos.datastructure.algorithm
+
+
+/**
+ * 迭代算法又称辗转法,一般求解数学问题,如一元高次方程,线性和非线性方程和曲线拟合等问题,一般用来求出解或者近似解
+ *
+ * 1. 确定迭代变量
+ *
+ * 2. 确定迭代递推关系
+ *
+ * 3. 确定迭代终止条件
+ *
+ *
+ *
+ *
+ * 欧几里得算法,两个整数的最大公约数等于其中较小的那个数和两数相除余数的最大公约数
+ *
+ * 所以拿到较小的数和余数再次进行这条规则,直到余数为0,返回除数
+ *
+ * Greatest Common Divisor 最大公约数
+ */
+
+
+fun main(args: Array) {
+
+ var a = 26
+ var b = 8
+
+ println("求解 $a 和 $b 的最大公约数")
+
+ println("迭代算法的实现;" + getGCD(a, b))
+
+ println("递归算法的实现;" + getGCDByRecursion(a, b))
+
+}
+
+/**
+ * 欧几里得 辗转相除法
+ */
+fun getGCD(first: Int, second: Int): Int? {
+
+ var a = first
+ var b = second
+
+ if (a < b) {
+ var temp = a
+ a = b
+ b = a
+ }
+
+ while (b > 0) {//终止条件除数为0
+ var c = a % b
+ a = b
+ b = c
+ }
+
+ return a
+}
+
+fun getGCDByRecursion(first: Int, second: Int): Int {
+
+ var a = first
+ var b = second
+ if (a < b) {
+ var temp = a
+ a = b
+ b = a
+ }
+ var c = a % b
+
+ if (c == 0) {
+ return b
+ } else {
+ return getGCDByRecursion(b, c)
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/NEmpress.java b/app/src/main/java/com/wangpos/datastructure/algorithm/NEmpress.java
new file mode 100644
index 0000000..5597c9c
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/NEmpress.java
@@ -0,0 +1,69 @@
+package com.wangpos.datastructure.algorithm;
+
+public class NEmpress {
+
+ public static void main(String[] args) {
+ // 4 == 2
+ // 1 == 1
+ // 2 3 == 0
+
+ // 8 ==92
+ Queen queen = new Queen(5);
+ queen.backtrack(1);
+ }
+
+}
+
+
+ class Queen {
+ private int[] column; //同栏是否有皇后,1表示有
+ private int[] rup; //右上至左下是否有皇后
+ private int[] lup; //左上至右下是否有皇后
+ private int[] queen; //解答
+ private int num; //解答编号
+ private int n = 1;
+
+ public Queen(int N) {
+ this.n = N;
+ column = new int[n+1];
+ rup = new int[(2*n)+1];
+ lup = new int[(2*n)+1];
+ for (int i = 1; i <= n; i++)
+ column[i] = 0;
+ for (int i = 1; i <= (2*n); i++)
+ rup[i] = lup[i] = 0; //初始定义全部无皇后
+ queen = new int[n+1];
+ }
+
+ public void backtrack(int i) {
+ if (i > n) {
+ showAnswer();
+ } else {
+ for (int j = 1; j <= n; j++) {
+ if ((column[j] == 0) && (rup[i+j] == 0) && (lup[i-j+n] == 0)) {
+ //若无皇后
+ queen[i] = j; //设定为占用
+ column[j] = rup[i+j] = lup[i-j+n] = 1;
+ backtrack(i+1); //循环调用
+ column[j] = rup[i+j] = lup[i-j+n] = 0;
+ }
+ }
+ }
+ }
+
+ protected void showAnswer() {
+ num++;
+ System.out.println("\n解答" + num);
+ for (int y = 1; y <= n; y++) {
+ for (int x = 1; x <= n; x++) {
+ if(queen[y]==x) {
+ System.out.print("Q");
+ } else {
+ System.out.print(".");
+ }
+ }
+ System.out.println();
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/QuickSort.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/QuickSort.kt
new file mode 100644
index 0000000..64b2856
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/QuickSort.kt
@@ -0,0 +1,51 @@
+package com.wangpos.datastructure.algorithm
+
+import android.util.Log
+import java.util.*
+
+fun main(args: Array) {
+
+ var arrays = arrayOf(2, 21, 13, 45, 55, 36, 17, 18, 99, 10)
+
+ println("待排序的队列 ${arrays.toList()}")
+ quickSort(arrays, 0, arrays.size-1)
+ println("已排序的队列 ${arrays.toList()}")
+
+}
+
+fun quickSort(arrays: Array, start: Int, end: Int) {
+ if (start >= end) {
+ return
+ }
+ var flagIndex = quickUnitSort(arrays, start, end)
+ quickSort(arrays, start, flagIndex - 1)
+ quickSort(arrays, flagIndex + 1, end)
+}
+
+fun quickUnitSort(arrays: Array, start: Int, end: Int): Int {
+ var low = start
+ var high = end
+ var key = arrays[low]
+ while (low < high) {
+ while (arrays[high] >= key && low < high) {
+ --high
+ }
+ arrays[low] = arrays[high]
+ while (arrays[low] <= key && low < high) {
+ ++low
+ }
+ arrays[high] = arrays[low]
+ }
+ var meetPosition: Int = low
+ arrays[meetPosition] = key
+ return meetPosition
+
+}
+
+
+fun swap(arrays: Array, i: Int, start: Int) {
+ var temp = arrays[start]
+ arrays[start] = arrays[i]
+ arrays[i] = temp
+}
+
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringAnagram.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringAnagram.java
new file mode 100644
index 0000000..418cba9
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringAnagram.java
@@ -0,0 +1,56 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringAnagram {
+
+ public static void main(String[] args) {
+ String targetString1 = "abcee";
+ String targetString2 = "bcdea";
+
+ boolean result = isDeformation(targetString1, targetString2);
+
+ System.out.println("结果:" + result);
+
+ }
+
+ /**
+ * 为什么要创建256个长度数组
+ *
+ * ASCII编码表中一共有256个字符
+ *
+ * 前128个为常用的字符 如 运算符 字母 数字等 键盘上可以显示的
+ * 后 128个为 特殊字符 是键盘上找不到的字符
+ *
+ * // 为什么有小于0 就是false,
+ * //首先前提我们判断过是长度相等的
+ * //如果chas1 中种类多和chas1种类数量不一样,就一定会出现负数,
+ * //出现负数有两种,第一种是种类多的变为负数,第二种是没有的变为负数
+ * @param targetString1
+ * @param targetString2
+ * @return
+ */
+ private static boolean isDeformation(String targetString1,
+ String targetString2) {
+ if (targetString1 == null || targetString2 == null
+ || targetString1.length() != targetString2.length()
+ ) {
+ return false;
+ }
+
+ char[] chas1 = targetString1.toCharArray();
+ char[] chars2 = targetString2.toCharArray();
+ //
+ int[] map = new int[256];
+
+ for (char c : chas1) {
+ map[c]++;
+ }
+ for (char c2 : chars2) {
+ map[c2]--;
+ if (map[c2] < 0) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringArraySearchString.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringArraySearchString.java
new file mode 100644
index 0000000..ec7f83b
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringArraySearchString.java
@@ -0,0 +1,51 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringArraySearchString {
+
+ public static void main(String args[]) {
+ String str = "a";
+
+ String[] strArrays = new String[]{null, "a", null, "a", null, "b", null, "c"};
+
+ System.out.println(getIndex(strArrays, str));
+ }
+
+ //二分法查找,
+ private static int getIndex(String[] strs, String str) {
+ if (strs == null || strs.length == 0 || str == null) {
+ return -1;
+ }
+ int res = -1;
+ int left = 0;
+ int right = strs.length - 1;
+ int mid = 0;
+ int i = 0;
+
+ while (left < right) {
+ mid = (left + right) / 2;
+ if (strs[mid] != null && strs[mid].equals(str)) {
+ res = mid;//返回最左边,所以要继续遍历
+ right = mid - 1;
+ } else if (strs[mid] != null) {
+ if (strs[mid].compareTo(str) < 0) {
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ } else {
+ i = mid;
+ while (strs[i] == null && --i >= left) ;
+
+ if (i < left || strs[i].compareTo(str) < 0) {
+ left = mid + 1;
+ } else {
+ res = strs[i].equals(str) ? i : res;
+ right = i - 1;
+ }
+ }
+ }
+
+
+ return res;
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringBracketStringInValid.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringBracketStringInValid.java
new file mode 100644
index 0000000..516f8cd
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringBracketStringInValid.java
@@ -0,0 +1,79 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.Arrays;
+import java.util.Stack;
+
+public class StringBracketStringInValid {
+
+ public static void main(String[] args) {
+
+ String str = "()()()";
+ String str2 = "((()()(()(";
+ String str3 = "121()()()";
+ System.out.println("result=" + inValidBracketString(str));
+ System.out.println("result=" + inValidBracketString(str3));
+
+ String str4 = "())";
+
+ String str5 = "()(()()(";
+
+ System.out.println(maxLengthBrcketString(str4));
+
+ System.out.println(maxLengthBrcketString(str5));
+ }
+
+ public static boolean inValidBracketString(String origin) {
+ char[] arrays = origin.toCharArray();
+ Stack stack = new Stack();
+
+ for (char data : arrays) {
+ if (data != '(' && data != ')') {
+ return false;
+ }
+ if (stack.isEmpty()) {
+ stack.push(data);
+ } else {
+ char top = stack.peek();
+ if (top == '(' && data == ')') {
+ stack.pop();
+ } else {
+ stack.push(data);
+ }
+ }
+ }
+
+ if (stack.isEmpty()) {
+ return true;
+ }
+ return false;
+ }
+
+
+ public static int maxLengthBrcketString(String origin) {
+ char[] arrays = origin.toCharArray();
+ int length = arrays.length;
+ int dp[] = new int[length];
+ //dp的值代表以当前结尾最长有效子串长度,什么意思? 比如()( dp[0]=0 dp[1]=2 dp[2] = 0
+ //(这里我会有疑问,我们以为dp[2]= 2 其实不是
+ // (() dp[2] = 2 如果结尾是) 从后向前找有效数量
+ // ()(() dp[4] = 2 从后向前找到
+ //()(()() dp[6] = 4 pre = 5 pre-1 = 4 dp[pre-1] = 2
+ //()()) dp[4] = 0
+ dp[0] = 0;
+ int pre = 0;
+ int res = 0;
+ for (int i = 1; i < arrays.length; i++) {
+ if (arrays[i] == ')') {
+ pre = i - dp[i - 1] - 1;
+ if (pre >= 0 && arrays[pre] == '(') {
+ //()(()())
+ dp[i] = dp[i - 1] + 2 + (pre > 0 ? dp[pre - 1] : 0);
+ }
+ }
+ res = Math.max(res, dp[i]);
+ }
+ System.out.println(Arrays.toString(dp));
+ return res;
+ }
+
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringContactMinDictionaryRank.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringContactMinDictionaryRank.java
new file mode 100644
index 0000000..eee0241
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringContactMinDictionaryRank.java
@@ -0,0 +1,37 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.Arrays;
+import java.util.Comparator;
+
+
+/**
+ * 排序比较就可以了,重要的是排序条件
+ */
+public class StringContactMinDictionaryRank {
+
+ public static void main(String[] args) {
+ String[] strArray = new String[]{"abc", "bcd", "acd"};
+
+ System.out.println(lowString(strArray));
+
+ }
+
+ public static class MyComparator implements Comparator{
+ @Override
+ public int compare(String o1, String o2) {
+ return (o1+02).compareTo(o2+o1);
+ }
+ }
+ public static String lowString(String[] strs) {
+ if (strs == null || strs.length == 0) {
+ return "";
+ }
+
+ Arrays.sort(strs, new MyComparator());
+ String res = "";
+ for (int i = 0; i < strs.length; i++) {
+ res += strs[i];
+ }
+ return res;
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringFormulaCalculate.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringFormulaCalculate.java
new file mode 100644
index 0000000..9894ef4
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringFormulaCalculate.java
@@ -0,0 +1,213 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.Deque;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.LinkedBlockingQueue;
+
+/**
+ * 支持整数加减乘除公式
+ */
+public class StringFormulaCalculate {
+
+ public static void main(String[] args) {
+ /**
+ * 加减法计算
+ */
+ String formula = "1+2-1+5-6";
+ /**
+ * 加减乘
+ */
+ String formula1 = "1+2*3"; //7
+ String formula2 = "1+2*3+4"; //11
+// String formula3 = "1*2+3+4"; //9
+ String formula4 = "1-2+3*4+6/2";//14
+
+ String formula5 = "2*(4-2)+5";
+
+ String formula6 = "2*(4-2)";
+
+ String formula7 = "(4-2)*2";
+ String formula8 = "10*((5-2)-2)";
+ String formula9 = "48*((70-65)-43)+8*1";
+// String formula = "48*((70-65)-43)+8*1";
+// String formula = "48*((70-65)-43)+8*1";
+
+// calculate(formula1, 0);
+// calculate(formula2, 0);
+// calculate(formula3, 0);
+// calculate(formula4,0);
+ calculate(formula9, 0);
+ Deque queues2 = queues;
+ System.out.println("结果" + queues);
+ }
+
+ /**
+ * 存储 数字和运算符
+ */
+ private static Deque queues = new LinkedList<>();
+
+ private static void addLastNum(Integer cur) {
+ String curNum = cur.toString();
+ if (queues.size() > 1) {
+ String sign = queues.removeLast();
+ String prev = queues.removeLast();
+ int result = calculateExpress(prev, curNum, sign);
+ queues.add(String.valueOf(result));
+ } else {
+ queues.add(curNum);
+ }
+ if (queues.size() > 1) {
+ String last = queues.removeLast();
+ addLastNum(Integer.valueOf(last));
+ }
+ }
+
+ /**
+ * 新加元素进行判断,如果前面是* / 直接运算,然后存入
+ * 如果+ - 暂时不运算
+ */
+ private static void addNum(Integer cur) {
+ String curNum = cur.toString();
+ String sign = queues.peekLast();
+ if ("*".equals(sign) || "/".equals(sign)) {
+ queues.removeLast();
+ String lastNum = queues.pollLast();
+ int result = calculateExpress(lastNum, curNum, sign);
+ queues.add(String.valueOf(result));
+ } else if ("+".equals(sign) || "-".equals(sign)) {
+ queues.add(curNum);
+ } else {
+ queues.add(curNum);
+ }
+ }
+
+ /**
+ * 如果+ - ,前两个有值运算前两个
+ * 否者直接加入
+ *
+ * @param sign
+ */
+ private static Integer addSign(char sign) {
+ if (sign == '+' || sign == '-' || sign == '(') {
+ String last = queues.peekLast();
+ if ("(".equals(last) || queues.size() < 2) {
+ } else if (queues.size() > 2) {
+ String prev1 = queues.removeLast();
+ String s = queues.removeLast();
+ String prev3 = queues.removeLast();
+ if ("(".equals(prev1)||"(".equals(s)||"(".equals(prev3)){
+ queues.add(prev3);
+ queues.add(s);
+ queues.add(prev1);
+ }else {
+ int result = calculateExpress(prev3, prev1, s);
+ queues.add(String.valueOf(result));
+ }
+ }
+ queues.add(String.valueOf(sign));
+ } else if (sign == '*' || sign == '/') {
+ queues.add(String.valueOf(sign));
+ }
+
+ if (sign == ')') {
+ String prev1 = queues.removeLast();
+ String s = queues.removeLast();
+ String prev3 = queues.removeLast();
+ int result = calculateExpress(prev3, prev1, s);
+ queues.removeLast();//移除左括号
+ queues.add(String.valueOf(result));
+ return result;
+ }
+ return 0;
+ }
+
+ /**
+ * 结果表示 遍历到哪一位,和计算结果
+ *
+ * @param formula
+ * @param
+ * @return
+ */
+ private static int[] calculate(String formula, int index) {
+
+ int s1 = 0;
+
+ char[] f = formula.toCharArray();
+ for (int i = index; i < formula.length(); i++) {
+ if (isNumber(f[i])) {
+ //转数字
+ s1 = s1 * 10 + f[i] - '0';
+
+ } else if (isSign(f[i])) {
+ // 运算符前一定有数字
+ if(s1>0) {
+ addNum(s1);
+ s1 = 0;
+ }
+ addSign(f[i]);
+ } else if (f[i] == '(') {
+ addSign(f[i]);
+ int result[] = calculate(formula, i + 1);
+ i = result[1];
+ //记录回溯的位置,因为后面还可能有元素要处理
+ //比如 1 + 2 *( 3 + 4 )+ 5
+ } else if (f[i] == ')') {
+ addNum(s1);
+ int result = addSign(f[i]);
+ s1 = 0;
+ return new int[]{result, i};
+ }
+
+ }
+ /**
+ * 综合计算
+ */
+ if (s1 != 0) {
+ addLastNum(s1);
+ s1 = 0;
+ }else{
+ if(queues.size()>1){
+ String last = queues.removeLast();
+ addLastNum(Integer.valueOf(last));
+ }
+ }
+
+ return new int[]{0, formula.length()};
+ }
+
+ private static boolean isSign(char c) {
+ if (c == '*' || c == '/' || c == '-' || c == '+') {
+ return true;
+ }
+ return false;
+ }
+
+ private static boolean isNumber(char c) {
+ return c >= '0' && c <= '9';
+ }
+
+ private static int calculateExpress(String s1, String s2, String sign) {
+ int num1 = Integer.parseInt(s1);
+ int num2 = Integer.parseInt(s2);
+ int result = 0;
+ switch (sign) {
+ case "*":
+ result = num1 * num2;
+ break;
+ case "/":
+ result = num1 / num2;
+ break;
+ case "+":
+ result = num1 + num2;
+ break;
+ case "-":
+ result = num1 - num2;
+ break;
+ }
+ return result;
+ }
+
+
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringFullArrangement.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/StringFullArrangement.kt
new file mode 100644
index 0000000..fc39e51
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringFullArrangement.kt
@@ -0,0 +1,64 @@
+package com.wangpos.datastructure.algorithm
+
+import java.util.Collections.swap
+
+/**
+ * 分治法,顾名思义分而治之,将无法着手的大问题分解成一系列相同的小问题,然后逐一解决
+ *
+ * 分治算法基本上可以归纳为三个步骤
+ *
+ * 1. 分解:将问题分解为若干规模小的相同结构问题
+ *
+ * 2. 解决:如果上一步问题可以解决就解决,否则,对每个子问题使用和上一步相同的方法再次分解,然后求解分解后的子问题,这个过程可能是一个递归的过程
+ *
+ * 3. 合并:将上一步解决的各个子问题的解通过某种规则合并起来,得到原问题的解
+ *
+ * 分治法难点,如果将子问题分解,并将子问题的解合并,针对不同的问题,有不同的分解与合并的方式
+ *
+ * 递归作为一种算法的实现方式,与分治是一✅天然的好朋友。当然分治也可以用非递归方式实现出来,就是比较难
+ *
+ *
+ */
+fun main(args: Array) {
+
+
+ var target = "abc"
+ var targetArray = target.toCharArray()
+
+ var resultList = arrayListOf()
+
+ stringFullArrangement(resultList, targetArray, 0, target.length)
+ println("输出字符串:$target 的所有排列")
+ println("全部排列方式:$resultList")
+
+}
+
+/**
+ * 以 a b 为例 ,第一次固定 a 不用交换(集合中还是 a,b)子集合还剩b, b start等于end 添加 ab,
+ *
+ * 第二次循环 ab 交换 (ba) 子集合还剩 a start等于end 添加 ba
+ *
+ * ba 交换回来 ab
+ */
+fun stringFullArrangement(resultList: ArrayList, target: CharArray, start: Int, end: Int) {
+
+ if (start == end) {//相等表示就一个字母不需要全排列了
+ println("add"+target.toList().toString()+"start$start")
+ resultList.add(target.toList().toString())
+ }
+ for (i in start until end) {
+ swap(target, i, start)//start表示固定的位置,每个元素都换到start位置,其他在去全排列,
+ stringFullArrangement(resultList,target,start+1,end)
+ swap(target, i, start)//进行下一个字符固定时要将上一个固定的位置还原到原来位置
+ }
+
+}
+
+fun swap(target: CharArray, first: Int, start: Int) {
+ if (target[first] != target[start]) {
+ var temp = target[first]
+ target[first] = target[start]
+ target[start] = temp
+ }
+}
+
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringGetMinCut.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringGetMinCut.java
new file mode 100644
index 0000000..31546c2
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringGetMinCut.java
@@ -0,0 +1,19 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringGetMinCut {
+
+ public static void main(String[]args){
+
+ String originStr = "ACDCDCDAD";
+
+
+ //A 0
+ //AC 1
+ // ACD 2
+ // ACDC 1
+ // ACDCD 2
+ // ACDCDC 2
+
+
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringISRotation.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringISRotation.java
new file mode 100644
index 0000000..59c448c
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringISRotation.java
@@ -0,0 +1,38 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringISRotation {
+
+ public static void main(String[] args) {
+
+ String a = "abcd1";
+ String b = "1abcd";
+
+ boolean result = isRotation(a, b);
+
+ System.out.println("结果:" + result);
+ }
+
+ private static boolean isRotation(String a, String b) {
+ if (a == null || b == null || a.length() != b.length()) {
+ return false;
+ }
+ String b2 = b + b;
+ return StringKMP.getIndexOf(b2,a)!=-1;
+ }
+
+ //KMP算法求是否包含子串 ,时间复杂度O(n+p)
+ private static int getIndexOf(String s, String m) {
+
+ if (s == null || m == null || m.length() < 1 || s.length() < m.length()) {
+ return -1;
+ }
+
+ char[] ss = s.toCharArray();
+ char[] ms = m.toCharArray();
+ int si = 0;
+ int mi = 0;
+// int []next = getNextArray(ms);
+ return 0;
+
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringKMP.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringKMP.java
new file mode 100644
index 0000000..a371502
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringKMP.java
@@ -0,0 +1,74 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringKMP {
+
+ public static void main(String[] args) {
+ String str1 = "ababacdcdefcdcag";
+ String str2 = "cdca";
+
+ System.out.println(getIndexOf(str1, str2));
+ }
+
+ static int getIndexOf(String source, String target) {
+ return kmp(source.toCharArray(), target.toCharArray());
+ }
+
+ static int kmp(char[] s, char[] p) {
+ int nextLength = Math.min(s.length, p.length);
+ int i = 0;
+ int j = 0;
+ int[] next = new int[nextLength];
+ getNextVal(p, next);
+ int sLen = s.length;
+ int pLen = p.length;
+ while (i < sLen && j < pLen) {
+ //①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++
+ if (j == -1 || s[i] == p[j]) {
+ i++;//等于-1 和匹配成功都++,为什么-1还++,表示前面还没有匹配成功
+ j++;
+ } else {
+ //②如果j != -1,且当前字符匹配失败(即S[i] != P[j]),则令 i 不变,j = next[j]
+ //next[j]即为j所对应的next值
+ j = next[j];
+ }
+ }
+ if (j == pLen)
+ return i - j; //返回p在S中的位置
+ else
+ return -1;
+ }
+
+
+ /**
+ * 获取K值数组
+ *
+ * @param p
+ * @param next
+ *
+ */
+ static void getNextVal(char[] p, int next[]) {
+ int pLen = p.length;
+ next[0] = -1;
+ int k = -1;
+ int j = 0;
+ while (j < pLen-1) {
+ //p[k]表示前缀,p[j]表示后缀
+ if (k == -1 || p[j] == p[k]) {
+ j++;
+ k++;
+// next[j] = k;
+
+ if (p[j] != p[k])
+ next[j] = k; //之前只有这一行
+ else
+ //因为不能出现p[j] = p[ next[j ]],所以当出现时需要继续递归,k = next[k] = next[next[k]]
+ next[j] = next[k];
+
+ } else {
+ k = next[k];
+
+ }
+ }
+
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringMaxLengthNoRepeatSequence.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMaxLengthNoRepeatSequence.java
new file mode 100644
index 0000000..ccb5e76
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMaxLengthNoRepeatSequence.java
@@ -0,0 +1,45 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringMaxLengthNoRepeatSequence {
+
+ public static void main(String[] args) {
+ String str = "abcdaef";
+ String str2 = "abcdaefd";
+ System.out.println(getMaxLengthNoRepeatSequence(str2));
+
+ }
+
+ /**
+ * 分析
+ * abcda
+ * 当我们编译如果不之前没有出现过就算在内,如果出现过就保存当前不重复长度,
+ * 然后将启示位置跳转到重复元素第一次出现的地方,比如重复元素默认位置是-1
+ * 当array[4]位置又出现a ,判断曾经出现过,
+ * 我们保存元素可以使用一个256数组即可,数组里面对应位置保存的是对应位置
+ *
+ * @param s
+ * @return
+ */
+ public static int getMaxLengthNoRepeatSequence(String s) {
+ if (s == null || s.equals("")) {
+ return 0;
+ }
+ char[] chas = s.toCharArray();
+ int[] map = new int[256];
+ for (int i = 0; i < 256; i++) {
+ map[i] = -1;
+ }
+ int len = 0;//最长长度
+ int pre = -1;//保存前一个位置
+ int cur = 0;//保存当前位置到前一个重复位置的长度
+ for (int i = 0; i != chas.length; i++) {
+ //重复字符串的头部,如果map[chas[i]]有值,证明就是重复的
+ pre = Math.max(pre, map[chas[i]]);
+ cur = i - pre;
+ len = Math.max(len, cur);
+ map[chas[i]] = i;
+ }
+ return len;
+ }
+
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringMerged.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMerged.java
new file mode 100644
index 0000000..274a887
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMerged.java
@@ -0,0 +1,92 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.HashSet;
+import java.util.List;
+
+/**
+ * 两个集合映射组合算法
+ *
+ */
+public class StringMerged {
+
+ public static int N = 262144;//9组数据
+ private static String[] resultArray = new String[262144];
+ private static int itemSize = 4;//每次最大4个
+ public static int index = 0;
+ private static HashSet sets = new HashSet<>();
+
+ public HashSet findAllKindSplice(String str) {
+ sets.clear();//每次都清理掉集合
+ char[] chas = new char[itemSize];
+
+ char[] strArray = str.toCharArray();
+ for (int i = 0; i < chas.length; i++) {
+ chas[i] = ' ';
+ if (i < str.length()) {
+ chas[i] = strArray[i];
+ }
+ }
+
+ int length = itemSize;
+ for (int i = 0; i < resultArray.length; i++) {
+ char chasValue = ' ';
+ if (index == 0) {
+ if (i < N / length) {
+ chasValue = chas[0];
+ } else if (i < N / length * 2) {
+ chasValue = chas[1];
+ } else if (i < N / length * 3) {
+ chasValue = chas[2];
+ } else if (i < N) {
+ if (chas[3] != ' ') {
+ chasValue = chas[3];
+ } else {
+// chasValue = '*';
+ }
+ }
+ } else {
+ if (i % getCount(N, index - 1) < getCount(N, index)) {//0~3
+ chasValue = chas[0];
+ } else if (i % getCount(N, index - 1) < getCount(N, index) * 2) {
+ chasValue = chas[1];
+ } else if (i % getCount(N, index - 1) < getCount(N, index) * 3) {
+ chasValue = chas[2];
+ } else if (i % getCount(N, index - 1) < getCount(N, index) * 4) {
+ if (chas[3] != ' ') {
+ chasValue = chas[3];
+ }
+ }
+ }
+
+ if (resultArray[i] != null && chasValue != ' ') {
+ resultArray[i] = resultArray[i] + chasValue;
+ } else {
+ if (chasValue != ' ') {
+ resultArray[i] = "" + chasValue;
+ } else {
+ resultArray[i] = "";
+ }
+ }
+ //去掉多于元素,因为本次拼接长度一定比上次长
+ if (resultArray[i].length() > index) {
+ sets.add(resultArray[i]);
+ }
+ }
+
+ index++;
+// return resultArray;
+ return sets;
+ }
+
+ private static int getCount(int n, int index) {
+ if (index == 0) {
+ return n / itemSize;
+ } else {
+ return getCount(n / itemSize, --index);
+ }
+ }
+
+
+
+
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringMerged2.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMerged2.java
new file mode 100644
index 0000000..de97105
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMerged2.java
@@ -0,0 +1,94 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * 两个集合映射组合算法
+ */
+public class StringMerged2 {
+ public static Node root = new Node(null, "", null);
+
+ public static List currentNodeList = new ArrayList<>();
+
+ public static void main(String[] args) {
+ String str1 = "ABC";
+ String str2 = "DEF";
+ String str3 = "GHI";
+ String str4 = "JKL";
+ String str5 = "MNO";
+ String str6 = "PQRS";
+ String str7 = "TUVW";
+ String str8 = "XYZ";
+ findMerged(str1);
+ findMerged(str2);
+ findMerged(str3);
+ findMerged(str4);
+ findMerged(str5);
+ findMerged(str6);
+ findMerged(str7);
+
+ System.out.println("start=" + System.currentTimeMillis());
+ List results = findMerged(str8);
+ System.out.println("end=" + System.currentTimeMillis());
+// for (Leaf leaf : currentLeafList) {
+// System.out.print(leaf.value + ",");
+// }
+
+ System.out.println("总结果数量:" + results.size());
+// for (String result : results) {
+// System.out.print(result + ",");
+// }
+
+// List results = findMerged(str1);
+ }
+
+ public static List findMerged(String str) {
+ char chas[] = str.toCharArray();
+
+ if (currentNodeList.size() == 0) {
+ List list = new ArrayList<>();
+ for (char cha : chas) {
+ list.add(new Node(root, String.valueOf(cha), null));
+ }
+ currentNodeList = list;
+ } else {
+ List nodeList = new ArrayList<>();//底部叶子节点
+ for (Node node : currentNodeList) {
+ List childList = new ArrayList<>();//创建每一个孩子集合
+ for (char cha : chas) {
+ Node child = new Node(node, String.valueOf(cha), null);
+ childList.add(child);
+ nodeList.add(child);
+ }
+ node.childs = childList;
+ }
+ currentNodeList = nodeList;
+ }
+
+ List results = new ArrayList<>();
+ for (Node node : currentNodeList) {
+ String end = "";
+ Node current = node;
+ while (current != null) {
+ end = current.value + end;
+ current = current.parent;
+ }
+ results.add(end);
+ }
+ return results;
+ }
+
+
+ static class Node {
+ public Node parent;
+ public String value;
+ public List childs;
+
+ public Node(Node p, String value, List childs) {
+ this.parent = p;
+ this.childs = childs;
+ this.value = value;
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringMinIncludeStringLength.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMinIncludeStringLength.java
new file mode 100644
index 0000000..496bd40
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMinIncludeStringLength.java
@@ -0,0 +1,4 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringMinIncludeStringLength {
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringMinShortDistance.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMinShortDistance.java
new file mode 100644
index 0000000..52838d7
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringMinShortDistance.java
@@ -0,0 +1,42 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringMinShortDistance {
+
+ public static void main(String args[]) {
+
+ String[] strings = new String[]{"1", "3", "3", "3", "2", "3", "1"};
+ System.out.println(minDistance(strings, "2", "1"));
+
+ }
+
+ public static int minDistance(String[] strs, String str1, String str2) {
+ if (str1 == null || str2 == null) {
+ return -1;
+ }
+ if (str1.equals(str2)) {
+ return 0;
+ }
+ int last1 = -1;
+ int last2 = -1;
+ int min = Integer.MAX_VALUE;
+ for (int i = 0; i != strs.length; i++) {
+ if (strs[i].equals(str1)) {
+ if (last2 != -1) {
+ min = Math.min(min, i - last2);
+ }
+ last1 = i;
+ }
+ if (strs[i].equals(str2)) {
+ if (last1 != -1) {
+ min = Math.min(min, i - last1);
+ }
+ last2 = i;
+ }
+ }
+
+ return min == Integer.MAX_VALUE ? -1 : min;
+ }
+
+ //如果实现时间复杂度O(1),那么我们只能采用Hash表,因为两个参数,所以Value 还得用一个hash表
+ //最后我们把这个表先生成就好了
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringNewString.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringNewString.java
new file mode 100644
index 0000000..c9c1362
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringNewString.java
@@ -0,0 +1,4 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringNewString {
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringPerfectShuffleCard.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringPerfectShuffleCard.java
new file mode 100644
index 0000000..2c801ca
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringPerfectShuffleCard.java
@@ -0,0 +1,55 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.Arrays;
+
+public class StringPerfectShuffleCard {
+ public static int N;
+ public static char chas[];
+
+ public static void main(String args[]) {
+ String str = "12345678";
+ chas = str.toCharArray();
+ N = str.length() / 2;
+ System.out.println(shuffleCard(str));
+ }
+
+ public static String shuffleCard(String str) {
+
+ for (int i = 1; i < N; ) {
+ int startIndex = i;
+ int curIndex = -1;
+ char currentValue = ' ';
+ while (curIndex != startIndex) {
+ if (curIndex == -1) {
+ curIndex = startIndex;
+ int nextIndex = getNextPosition(curIndex);
+ currentValue = chas[nextIndex];
+ chas[nextIndex] = chas[curIndex];
+ curIndex = nextIndex;
+ } else {
+ int nextIndex = getNextPosition(curIndex);
+ char nextValue = chas[nextIndex];
+ chas[nextIndex] = currentValue;
+ currentValue = nextValue;
+ curIndex = nextIndex;
+ }
+ }
+
+ i = i + 2;
+ }
+
+ return Arrays.toString(chas);
+ }
+
+ private static char getValue(int curIndex) {
+ return chas[curIndex];
+ }
+
+ public static int getNextPosition(int postion) {
+ if (postion < N) {
+ return 2 * postion;
+ } else {
+ return 2 * (postion - N) + 1;
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringReplace.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringReplace.java
new file mode 100644
index 0000000..d39cc15
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringReplace.java
@@ -0,0 +1,53 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringReplace {
+
+ public static void main(String[] args) {
+
+
+ }
+
+ public static void replace(char[] chas) {
+ if (chas == null || chas.length == 0) {
+ return;
+ }
+ int num = 0;
+ int len = 0;
+ for (len = 0; len < chas.length && chas[len] != 0; len++) {
+ if (chas[len] == ' ') {
+ num++;
+ }
+ }
+
+ int j = len + num * 2 - 1;
+ for (int i = len - 1; i > -1; i--) {
+ if (chas[i] != ' ') {
+ chas[j--] = chas[i];
+ } else {
+ chas[j--] = '0';
+ chas[j--] = '2';
+ chas[j--] = '%';
+ }
+ }
+ }
+
+ /**
+ * 有字符串的包含数组和* ,现在把星移动到所有数字前面
+ * @param chas
+ */
+ public void modify(char[]chas){
+
+ if(chas ==null ||chas.length==0){
+ return;
+ }
+ int j = chas.length-1;
+ for(int i= chas.length-1;i>-1;i--){
+ if(chas[i]!='*'){
+ chas[j--] = chas[i];
+ }
+ }
+ for(;j>-1;){
+ chas[j--] = '*';
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringReverse.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringReverse.java
new file mode 100644
index 0000000..31bb719
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringReverse.java
@@ -0,0 +1,89 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.Arrays;
+
+public class StringReverse {
+
+
+ public static void main(String[] args) {
+
+ String str = "I love you";
+
+ String result = getReverse2(str);
+ System.out.println(result);
+
+ }
+
+ //通过char 数组事项
+ private static String getReverse(String str) {
+ char[] chas = str.toCharArray();
+ int start = 0;
+ int end = chas.length - 1;
+ /**
+ * 实现思路 先全部反转,然后再局部反转
+ */
+ reverse(chas, start, end);
+
+ int l = -1;
+ int r = -1;
+ for (int i = 0; i < chas.length; i++) {
+ if (chas[i] != ' ') {
+ //找到l
+ if (i == 0 || chas[i - 1] == ' ') {
+ l = i;
+ }
+ //找到每一个r
+ if (i == chas.length - 1 || chas[i + 1] == ' ') {
+ r = i;
+ }
+ }
+ if (l != -1 && r != -1) {
+ reverse(chas, l, r);
+ l = -1;
+ r = -1;
+ }
+ }
+
+ return Arrays.toString(chas);
+ }
+
+ //通过String 数组也可以实现,但是会产生临时对象
+ private static String getReverse2(String str) {
+ String strArray[] = str.split(" ");
+
+ int start = 0;
+ int end = strArray.length - 1;
+ String tmp = "";
+ while (start < end) {
+ tmp = strArray[start];
+ strArray[start] = strArray[end];
+ strArray[end] = tmp;
+ start++;
+ end--;
+ }
+
+ String result = "";//StringBuilder
+ for (int i = 0; i < strArray.length; i++) {
+ if (i == strArray.length - 1) {
+ result = result+strArray[i];
+ } else {
+ result = result + strArray[i] + " ";
+ }
+
+ }
+ return result;
+ }
+
+
+ public static void reverse(char[] chas, int start, int end) {
+ char tmp = 0;
+ while (start < end) {
+ tmp = chas[start];
+ chas[start] = chas[end];
+ chas[end] = tmp;
+ start++;
+ end--;
+ }
+ }
+
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringRotateChange.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringRotateChange.java
new file mode 100644
index 0000000..843a897
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringRotateChange.java
@@ -0,0 +1,52 @@
+package com.wangpos.datastructure.algorithm;
+
+
+/**
+ * 旋转字符串
+ *
+ *
+ */
+public class StringRotateChange {
+
+ public static void main(String[] args) {
+
+ String s1 = "abcd";
+ String s2 = "dbac";//true
+
+ System.out.println("是否是旋转串=" + isRotateString(s1, s2));
+
+ String s3 = "abcd";
+ String s4 = "cadb";//false
+
+ System.out.println("是否是旋转串=" + isRotateString(s3, s4));
+ }
+
+ public static boolean isRotateString(String s1, String s2) {
+ if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0 || s1.length() != s2.length()) {
+ return false;
+ }
+ if (s1 == s2) {
+ return true;
+ }
+
+ char[] chas1 = s1.toCharArray();
+ char[] chas2 = s2.toCharArray();
+
+ /**
+ * 从上向下比较
+ */
+ int start = 0;
+ int end = chas2.length-1;
+ for (int i = chas1.length-1; i >0; i--) {
+ if (chas1[i] != chas2[end]) {
+ if (chas1[i] != chas2[start]) {
+ return false;
+ } else {
+ start++;
+ }
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringSingleChar.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringSingleChar.java
new file mode 100644
index 0000000..142dbe9
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringSingleChar.java
@@ -0,0 +1,108 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringSingleChar {
+
+ public static void main(String[] args) {
+ String testStr1 = "aaabbb";
+ String testStr2 = "abcd";
+
+ System.out.println(isSingleCharString(testStr1));
+ System.out.println(isSingleCharString(testStr2));
+
+ System.out.println(isUnique2(testStr1.toCharArray()));
+ System.out.println(isUnique2(testStr2.toCharArray()));
+ }
+
+ // O (n)
+ public static boolean isSingleCharString(String str) {
+ char[] chars = str.toCharArray();
+ int[] counts = new int[256];
+ for (char aChar : chars) {
+ if (counts[aChar] > 0) {
+ return false;
+ }
+ counts[aChar]++;
+ }
+ return true;
+ }
+
+ // 要求空间复杂度O 1
+ /**
+ * 所有O(n)时间复杂度的排序算法(桶排序,基数排序,计数排序)都需要额外空间排序,所以空间复杂度不是O(1)
+ * 那么看O(nlogn)时间复杂度算法 (归并排序,快速排序,希尔排序,堆排序)
+ * 归并排序中有连个数组合并成一个数组过程,这个过程需要辅助数组来完成
+ * 快速排序额外空间复杂度最低 logN
+ * 希尔排序同样也排除,因为他的时间复杂度不固定,最低N*N,取决于步长
+ * 堆排序 可以时间复杂度能稳定O(NlogN) 并且空间复杂度是O(1),但是要使用非递归实现
+ * 否则会浪费函数栈空间
+ *
+ * @param chas
+ * @return
+ */
+ //堆排序 O(nlogn) 空间复杂度O(1)
+ public static boolean isUnique2(char[] chas) {
+
+ if (chas == null) {
+ return true;
+ }
+ heapSort(chas);
+ for (int i = 1; i < chas.length; i++) {
+ if (chas[i] == chas[i - 1]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static void heapSort(char[] chas) {
+ for (int i = 0; i < chas.length; i++) {
+ heapInsert(chas, i);
+ }
+ for (int i = chas.length - 1; i > 0; i--) {
+ swap(chas, 0, i);
+ heapify(chas, 0, i);
+ }
+ }
+
+ public static void heapify(char[] chas, int i, int size) {
+ int left = i * 2 + 1;
+ int right = i * 2 + 2;
+ int largest = i;
+ while ((left < size)) {
+ if (chas[left] > chas[i]) {
+ largest = left;
+ }
+ if (right < size && chas[right] > chas[largest]) {
+ largest = right;
+ }
+ if (largest != i) {
+ swap(chas, largest, i);
+ } else {
+ break;
+ }
+ i = largest;
+ left = i * 2 + 1;
+ right = i * 2 + 2;
+ }
+ }
+
+ public static void heapInsert(char[] chas, int i) {
+ int parent = 0;
+ while (i != 0) {
+
+ parent = (i - 1) / 2;
+ if (chas[parent] < chas[i]) {
+ swap(chas, parent, i);
+ i = parent;
+ } else {
+ break;
+ }
+ }
+ }
+
+ public static void swap(char[] chas, int index1, int index2) {
+ char tmp = chas[index1];
+ chas[index1] = chas[index2];
+ chas[index2] = tmp;
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringToDiKaEr.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringToDiKaEr.java
new file mode 100644
index 0000000..8aa4262
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringToDiKaEr.java
@@ -0,0 +1,103 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class StringToDiKaEr {
+
+
+ public static void main(String[] args) {
+ List> list = new ArrayList>();
+ List listSub1 = new ArrayList();
+ List listSub2 = new ArrayList();
+ List listSub3 = new ArrayList();
+ List listSub4 = new ArrayList();
+ List listSub5 = new ArrayList();
+ List listSub6 = new ArrayList();
+ List listSub7 = new ArrayList();
+ List listSub8 = new ArrayList();
+ listSub1.add("A");
+ listSub1.add("B");
+ listSub1.add("C");
+
+ listSub2.add("D");
+ listSub2.add("E");
+ listSub2.add("F");
+
+ listSub3.add("G");
+ listSub3.add("H");
+ listSub3.add("I");
+
+ listSub4.add("J");
+ listSub4.add("K");
+ listSub4.add("L");
+
+ listSub5.add("M");
+ listSub5.add("N");
+ listSub5.add("O");
+
+ listSub6.add("P");
+ listSub6.add("Q");
+ listSub6.add("R");
+
+ listSub7.add("S");
+ listSub7.add("T");
+ listSub7.add("U");
+
+ listSub8.add("V");
+ listSub8.add("W");
+ listSub8.add("X");
+
+
+ list.add(listSub1);
+ list.add(listSub2);
+ list.add(listSub3);
+ list.add(listSub4);
+ list.add(listSub5);
+ list.add(listSub6);
+ list.add(listSub7);
+ list.add(listSub8);
+
+ System.out.println("start:"+System.currentTimeMillis());
+ List> result = new ArrayList>();
+ descartes(list, result, 0, new ArrayList());
+ System.out.println("end:"+System.currentTimeMillis());
+ }
+ /**
+ * Created on 2014年4月27日
+ *
+ * Discription:笛卡尔乘积算法
+ * 把一个List{[1,2],[3,4],[a,b]}转化成List{[1,3,a],[1,3,b],[1,4
+ * ,a],[1,4,b],[2,3,a],[2,3,b],[2,4,a],[2,4,b]}数组输出
+ *
+ *
+ * @param layer
+ * 中间参数
+ * @param curList
+ * 中间参数
+ */
+ private static void descartes(List> dimvalue,
+ List> result, int layer, List curList) {
+ if (layer < dimvalue.size() - 1) {
+ if (dimvalue.get(layer).size() == 0) {
+ descartes(dimvalue, result, layer + 1, curList);
+ } else {
+ for (int i = 0; i < dimvalue.get(layer).size(); i++) {
+ List list = new ArrayList(curList);
+ list.add(dimvalue.get(layer).get(i));
+ descartes(dimvalue, result, layer + 1, list);
+ }
+ }
+ } else if (layer == dimvalue.size() - 1) {
+ if (dimvalue.get(layer).size() == 0) {
+ result.add(curList);
+ } else {
+ for (int i = 0; i < dimvalue.get(layer).size(); i++) {
+ List list = new ArrayList(curList);
+ list.add(dimvalue.get(layer).get(i));
+ result.add(list);
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringToInt.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringToInt.java
new file mode 100644
index 0000000..baf9199
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringToInt.java
@@ -0,0 +1,82 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringToInt {
+
+ public static void main(String[] args) {
+
+ String str = "-123";
+ String str2 = "a2342";
+ String str3 = "02342";
+ int result = convert(str);
+
+ System.out.println(result);
+ }
+
+ /**
+ * 检测是否是数字字符
+ *
+ * @param chas
+ * @return
+ */
+ public static boolean isValid(char[] chas) {
+ //判断第一位是0到9的之外的数,而不是负号
+ if (chas[0] != '-' && (chas[0] < '0' || chas[0] > '9')) {
+ return false;
+ }
+ //如果第一位为负号,后面的不可以是0 也不能没有值
+ if (chas[0] == '-' && (chas.length == 1 || chas[1] == '0')) {
+ return false;
+ }
+ //第一位是0 但是长度大于1 false
+ if (chas[0] == '0' && chas.length > 1) {
+ return false;
+ }
+
+ //第二位以后是0 到9的数
+ for (int i = 1; i < chas.length; i++) {
+ if (chas[i] < '0' || chas[i] > '9') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static int convert(String str) {
+ if (str == null || str.equals("")) {
+ return 0;//不能转
+ }
+ char[] chas = str.toCharArray();
+ if (!isValid(chas)) {
+ return 0;//不符合要求
+ }
+
+ //判断正负数
+ boolean posi = chas[0] != '-';
+ int minq = Integer.MIN_VALUE / 10;
+ int minr = Integer.MAX_VALUE % 10;
+ int res = 0;
+ int cur = 0;
+ //-2147483648 2147483647
+ //
+ //左程云. 程序员代码面试指南IT名企算法与数据结构题目最优解(第2版) (Chinese Edition) (Kindle位置3654). Kindle 版本.
+ //
+ //左程云. 程序员代码面试指南IT名企算法与数据结构题目最优解(第2版) (Chinese Edition) (Kindle位置3654). Kindle 版本.
+ //以负数进行计算 比如
+ // 123 第一次 -1 res = 0*10 -1 =-1 小于12
+ // 第二次 res = -1*10 -2 = -12 小于12 如果大于直接溢出,不管下一位是什么
+ // 第三次 res = -12*10 -3 = -123 如果等于 就比较最后一个值
+ for (int i = posi ? 0 : 1; i < chas.length; i++) {
+ cur = '0' - chas[i];//当前字符所代表的负数形式
+ if ((res < minq) || (res == minq && cur < minr)) {
+ return 0;
+ }
+ res = res * 10 + cur;
+
+ }
+ //判断正数最大值
+ if (posi && res == Integer.MIN_VALUE) {
+ return 0;//不能转
+ }
+ return posi ? -res : res;
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringToStatisticsString.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringToStatisticsString.java
new file mode 100644
index 0000000..39638a9
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringToStatisticsString.java
@@ -0,0 +1,39 @@
+package com.wangpos.datastructure.algorithm;
+
+public class StringToStatisticsString {
+
+
+ public static void main(String[] args) {
+
+ String target = "aaabbbbbccc3333cccdee";
+
+ String result = getCountString(target);
+
+ System.out.println(result);
+
+ }
+
+ public static String getCountString(String str) {
+
+ char[] chs = str.toCharArray();
+ String res = String.valueOf(chs[0]);
+
+ int num = 1;
+
+ for (int i = 1; i < chs.length; i++) {
+ if (chs[i] != chs[i - 1]) {
+ res = contact(res,String.valueOf(num),String.valueOf(chs[i]));
+ num = 1;
+ }else{
+ num++;
+ }
+ }
+ return contact(res,String.valueOf(num),"");
+ }
+
+ //统计字符串用_分割开,可以区分里面含数字的情况
+ public static String contact(String s1,String s2,String s3){
+ return s1+"_"+s2+(s3.equals("")?s3:"_"+s3);
+ }
+
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/StringToStringMinDistance.java b/app/src/main/java/com/wangpos/datastructure/algorithm/StringToStringMinDistance.java
new file mode 100644
index 0000000..415e87f
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/StringToStringMinDistance.java
@@ -0,0 +1,118 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Queue;
+import java.util.Set;
+
+public class StringToStringMinDistance {
+
+ public static void main(String[] args) {
+
+ String start = "adc";
+ String to = "cab";
+ List words = new ArrayList<>();
+ words.add("cab");
+ words.add("acc");
+ words.add("cbc");
+ words.add("ccc");
+ words.add("cac");
+ words.add("cbb");
+ words.add("aab");
+ words.add("abb");
+
+ List> list = findMinPaths(start, to, words);
+
+ for (List strings : list) {
+ for (String str:strings){
+ System.out.print(" "+str+" ");
+ }
+ System.out.println();
+ }
+ }
+
+ public static List> findMinPaths(String start, String to, List list) {
+ list.add(start);
+ HashMap> nexts = getNexts(list);
+ HashMap distances = getDistance(start, nexts);
+ LinkedList pathList = new LinkedList<>();
+ List> res = new ArrayList<>();
+ getShortestPaths(start, to, nexts, distances, pathList, res);
+ return res;
+ }
+
+ private static void getShortestPaths(String cur, String to, HashMap> nexts,
+ HashMap distances, LinkedList solution,
+ List> res) {
+ solution.add(cur);
+ if (to.equals(cur)) {
+ res.add(new LinkedList(solution));
+ } else {
+ for (String next : nexts.get(cur)) {
+ if (distances.get(next) == distances.get(cur) + 1) {
+ getShortestPaths(next, to, nexts, distances, solution, res);
+ }
+ }
+ }
+ solution.pollLast();
+ }
+
+
+ public static HashMap getDistance(String start, HashMap> nexts) {
+ HashMap distances = new HashMap<>();
+ distances.put(start, 0);
+ Queue queue = new LinkedList();
+ queue.add(start);
+ HashSet set = new HashSet<>();
+ set.add(start);
+ while (!queue.isEmpty()) {
+ String cur = queue.poll();
+ for (String str : nexts.get(cur)) {
+ if (!set.contains(str)) {
+ distances.put(str, distances.get(cur) + 1);
+ queue.add(str);
+ set.add(str);
+ }
+ }
+ }
+
+ return distances;
+ }
+
+ public static HashMap> getNexts(List words) {
+ Set dict = new HashSet<>(words);
+
+ HashMap> nexts = new HashMap<>();
+ for (int i = 0; i < words.size(); i++) {
+ nexts.put(words.get(i), new ArrayList());
+ }
+ for (int i = 0; i < words.size(); i++) {
+ nexts.put(words.get(i), getNext(words.get(i), dict));
+ }
+ return nexts;
+ }
+
+ private static ArrayList getNext(String word, Set dict) {
+ ArrayList res = new ArrayList<>();
+ char[] chs = word.toCharArray();
+ for (char cur = 'a'; cur <= 'z'; cur++) {
+ for (int i = 0; i < chs.length; i++) {
+ if (chs[i] != cur) {
+ char tmp = chs[i];
+
+ chs[i] = cur; //替换
+ if (dict.contains(String.valueOf(chs))) {
+ res.add(String.valueOf(chs));
+ }
+ chs[i] = tmp; //替换回来
+ }
+ }
+ }
+ return res;
+ }
+
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/TestStringMerged.java b/app/src/main/java/com/wangpos/datastructure/algorithm/TestStringMerged.java
new file mode 100644
index 0000000..cadf3b7
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/TestStringMerged.java
@@ -0,0 +1,54 @@
+package com.wangpos.datastructure.algorithm;
+
+import java.util.HashMap;
+import java.util.HashSet;
+
+public class TestStringMerged {
+
+ public static void main(String[] args) {
+
+ String str1 = "ABCD";
+
+ String str2 = "EFGH";
+
+ String str3 = "IJK";
+
+ String str4 = "LMN";
+
+ String str5 = "OPQ";
+
+ String str6 = "RST";
+
+ String str7 = "UVW";
+
+ String str8 = "XYZ";
+
+ StringMerged sm = new StringMerged();
+
+ sm.findAllKindSplice(str1);
+ sm.findAllKindSplice(str2);
+ sm.findAllKindSplice(str3);
+ sm.findAllKindSplice(str4);
+ sm.findAllKindSplice(str5);
+ sm.findAllKindSplice(str6);
+ sm.findAllKindSplice(str7);
+ System.out.println("startTime " + System.currentTimeMillis());
+ HashSet resultSet = sm.findAllKindSplice(str8);
+ System.out.println("endTime " + System.currentTimeMillis());
+
+
+// for (String s : resultArray) {
+// System.out.print(s + " ");
+// }
+
+ System.out.println();
+// System.out.println("______________________");
+////
+ System.out.println("种类" + resultSet.size());
+// for (String s : resultSet) {
+// System.out.print(s + " ");
+// }
+
+
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/TwoSeparate.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/TwoSeparate.kt
new file mode 100644
index 0000000..b711005
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/TwoSeparate.kt
@@ -0,0 +1,36 @@
+package com.wangpos.datastructure.algorithm
+
+
+fun main(args: Array) {
+
+ var result = twoSepearate(-0.8,8.0)
+
+ println("方程的近似解=$result")
+}
+
+/**
+ * 二分法的局限性就是不能计算复根和重根,需要借助其手段确定零点所在区间。设方程为 f(x) = 2x^{2} + 3.2x - 1.8f(x)=2x
+2
++3.2x−1.8,求根精度是 PRECISION = 0.000000001,在 [-0.8,8.0] 区间上求解 xx = 0.440967364
+ */
+fun f(x: Double): Double {
+ return 2.0 * x * x + 3.2 * x - 1.8
+}
+
+
+fun twoSepearate(aa: Double, bb: Double): Double {
+ var PRECISION = 0.00000000001
+ var a = aa
+ var b = bb
+ var mid = (a + b) / 2.0
+
+ while ((b - a) > PRECISION) {
+ if (f(a) * f(mid) < 0.0) {
+ b = mid
+ } else {
+ a = mid
+ }
+ mid = (a + b) / 2.0
+ }
+ return mid
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustion100buychicken.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustion100buychicken.kt
new file mode 100644
index 0000000..c0d1f2d
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustion100buychicken.kt
@@ -0,0 +1,62 @@
+package com.wangpos.datastructure.algorithm
+
+
+/**
+ *穷举法又称穷举搜索法,是一种在问题域的解空间中对所有可能的解穷举搜索,并根据条件选择最优解的方法的总称。
+ * 数学上也把穷举法称为枚举法,就是在一个由有限个元素构成的集合中,把所有元素一一枚举研究的方法。
+ *
+ * 穷举法的敌人就是规模大,解空间大
+ *
+ *一般来说,只要一个问题有其他更好的方法解决,通常不会选择穷举法,穷举法也常被作为“不是办法的办法”或“最后的办法”来使用,但是绝对不能因为这样而轻视穷举法,穷举法在算法设计模式中占有非常重要的地位,它还是很多问题的唯一解决方法。
+ *
+ *
+ *
+ */
+
+fun main(args: Array) {
+
+ var count = buychicken(100)
+
+ println("百钱买鸡共有 $count 种方法")
+
+}
+
+
+/**
+ *
+ * *
+ *一百个钱买一百只鸡,是个典型的穷举法应用。问题描述:每只大公鸡值 5 个钱,
+ * 每只母鸡值 3 个钱,
+ * 每 3 只小鸡值 1 个钱,
+ * 现在有 100 个钱,想买 100 只鸡,问如何买?有多少种方法?
+ *
+ * 公鸡枚举的空间 0 20
+ *
+ * 母鸡枚举的空间 0 33
+ */
+
+fun buychicken(money: Int): Int {
+
+ var maxGJ = 20
+
+ var maxMJ = 33
+
+ var count = 0
+
+ var startTime = System.currentTimeMillis()
+ for (i in 0 until 21) {
+ // 剪枝操作,提高效率
+ var maxCount = (100 - i*5)/3
+ for (j in 0 until maxCount) {
+ var smallChicken = 100 - i - j
+ if (smallChicken % 3 == 0 && (smallChicken / 3 + j * 3 + i * 5) == 100){
+ println("公鸡=$i ,母鸡=$j ,小鸡=$smallChicken")
+ count++
+ }
+ }
+ }
+ println("算法花费时间"+(System.currentTimeMillis()-startTime))
+
+
+ return count
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustion24.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustion24.kt
new file mode 100644
index 0000000..09ef959
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustion24.kt
@@ -0,0 +1,99 @@
+package com.wangpos.datastructure.algorithm
+
+import kotlin.reflect.KFunction3
+
+/**
+ *
+ * 穷举加分治法,子问题就是求两个数的四则运算
+ */
+fun main(args: Array) {
+
+ var arrays = arrayOf(::add, ::sub, ::multiply,::divide)
+ var nums = arrayListOf(
+ Number(3.toDouble(), "3"),
+ Number(2.toDouble(), "2"),
+ Number(6.toDouble(), "6"),
+ Number(7.toDouble(), "7")
+ )
+ Calc24(nums, arrays)
+
+}
+
+class Number(var num: Double, var num_str: String)
+
+fun add(number1: Number, number2: Number, next: (Number) -> Unit): Boolean {
+ var result = number1.num + number2.num
+ var newNumber = Number(result, "("+number1.num_str + "+" + number2.num_str+")")
+ next(newNumber)
+ return true
+}
+
+fun sub(number1: Number, number2: Number, next: (Number) -> Unit): Boolean {
+ var result = number1.num - number2.num
+ var newNumber = Number(result, "("+number1.num_str + "-" + number2.num_str+")")
+ next(newNumber)
+ return true
+}
+
+fun multiply(number1: Number, number2: Number, next: (Number) -> Unit): Boolean {
+ var result = number1.num * number2.num
+ var newNumber = Number(result, "("+number1.num_str + "*" + number2.num_str+")")
+ next(newNumber)
+ return true
+
+}
+
+fun divide(number1: Number, number2: Number, next: (Number) -> Unit): Boolean {
+ if (number2.num == 0.toDouble()) return false
+ var result = number1.num / number2.num
+// println("////$result")
+ var newNumber = Number(result, "("+number1.num_str + "/" + number2.num_str+")")
+ next(newNumber)
+ return true
+}
+
+fun Calc24(
+ nums: ArrayList,
+ operations: Array Unit, Boolean>>
+) {
+ if (nums.size == 1) {
+ if (nums[0].num.toInt() == 24) {
+ println(nums[0].num_str + "=" + nums[0].num)
+ }
+ return
+ }
+// println("---------")
+// nums.forEach {
+// println(it.num_str + "=" + it.num)
+// }
+// println("---------")
+
+ for (i in nums.indices) {
+ for (j in nums.indices) {
+ if (i == j) continue
+
+ operations.forEach {
+ var newNumber: Number? = null
+ if (it(nums[i], nums[j]) {
+ newNumber = it
+ }) {
+ var list = arrayListOf()
+
+ // 新数据添加集合
+ newNumber?.let { it1 -> list.add(it1) }
+
+ for (k in nums.indices) {
+ if (k == i || k == j) continue
+ // 将剩余数添加到集合
+ list.add(nums[k])
+ }
+
+ Calc24(list, operations)
+ }
+ }
+ }
+ }
+}
+
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionAlbertEinstein.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionAlbertEinstein.kt
new file mode 100644
index 0000000..729f66d
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionAlbertEinstein.kt
@@ -0,0 +1,508 @@
+package com.wangpos.datastructure.algorithm
+
+
+/**
+ * (1)英国人住在红色的房子里
+(2)瑞典人养狗作为宠物
+(3)丹麦人喝茶
+(4)绿房子紧挨着白房子,在白房子的左边
+(5)绿房子的主人喝咖啡
+(6)抽 Pall Mall 牌香烟的人养鸟
+(7)黄色房子里的人抽 Dunhill 牌香烟
+
+(8)住在中间那个房子里的人喝牛奶
+(9)挪威人住在第一个房子里面
+
+(10)抽 Blends 牌香烟的人和养猫的人相邻
+(11)养马的人和抽 Dunhill 牌香烟的人相邻
+(12)抽 BlueMaster 牌香烟的人喝啤酒
+(13)德国人抽 Prince 牌香烟
+(14)挪威人和住在蓝房子的人相邻
+(15)抽 Blends 牌香烟的人和喝矿泉水的人相邻
+ */
+val yellow = 1
+val blue = 2
+val red = 3
+val green = 4
+val white = 5
+
+val water = 1
+val tea = 2
+val milk = 3
+val coffee = 4
+val beer = 5
+
+val nuowei = 1
+val danmai = 2
+val yingguo = 3
+val deguo = 4
+val ruidian = 5
+
+val cat = 1
+val horse = 2
+val bird = 3
+val fish = 4
+val dog = 5
+
+val Dunhill = 1
+val Blends = 2
+val PallMall = 3
+val Prince = 4
+val BlueMaster = 5
+
+
+var roomColors = arrayOf(1, 2, 3, 4, 5)
+var drinks = arrayOf(1, 2, 3, 4, 5)
+var countrys = arrayOf(1, 2, 3, 4, 5)
+var pets = arrayOf(1, 2, 3, 4, 5)
+var tobaccos = arrayOf(1, 2, 3, 4, 5)
+
+var cnt: Long = 0
+
+/**
+ * 先填表,最后在赛选,也可以用递归实现
+ */
+fun main() {
+
+ var groups = arrayOf(Person_E(), Person_E(), Person_E(), Person_E(), Person_E())
+
+ assignedColor(roomColors, groups)
+}
+
+/**
+ * 分配颜色
+ */
+private fun assignedColor(
+ roomColors: Array,
+ groups: Array
+) {
+ for (i in roomColors.indices) {
+ for (j in roomColors.indices) {
+ if (i == j) continue
+ for (k in roomColors.indices) {
+ if (k == i || k == j) continue
+ for (l in roomColors.indices) {
+ if (l == i || l == j || l == k) continue
+ for (m in roomColors.indices) {
+ if (m == i || m == j || m == k || m == l) continue
+
+ groups[0].room_color = roomColors[i]
+ groups[1].room_color = roomColors[j]
+ groups[2].room_color = roomColors[k]
+ groups[3].room_color = roomColors[l]
+ groups[4].room_color = roomColors[m]
+ // 剪枝操作
+ // 再分配国家
+ for (groupIdx in groups.indices) {
+ if (groupIdx + 1 < groups.size) {
+ var ad = "sd"
+ ad.isEmpty()
+ if (groups[groupIdx].room_color === green
+ && groups[groupIdx + 1].room_color == white
+ ) {
+ assignedCountry(groups)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * 分配国家
+ */
+fun assignedCountry(groups: Array) {
+ /*应用规则(9):挪威人住在第一个房子里面;*/
+ groups[0].country = nuowei;
+
+ for (i in countrys.indices) {
+ for (j in countrys.indices) {
+ if (i == j) continue
+ for (k in countrys.indices) {
+ if (k == i || k == j) continue
+ for (l in countrys.indices) {
+ if (l == k || l == j || l == i) continue
+ for (m in countrys.indices) {
+ if (m == i || m == j || m == k || m == l) continue
+ groups[1].country = countrys[j]
+ groups[2].country = countrys[k]
+ groups[3].country = countrys[l]
+ groups[4].country = countrys[m]
+
+ assigndDrink(groups)
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * 分配喝的
+ */
+fun assigndDrink(groups: Array) {
+ /*应用规则(8):住在中间那个房子里的人喝牛奶;*/
+ groups[2].drink = milk
+ for (i in drinks.indices) {
+ for (j in drinks.indices) {
+ if (i == j) continue
+ for (k in drinks.indices) {
+ if (k == i || k == j) continue
+ for (l in drinks.indices) {
+ if (l == k || l == j || l == i) continue
+ for (m in drinks.indices) {
+ if (m == i || m == j || m == k || m == l) continue
+ groups[0].drink = drinks[i]
+ groups[1].drink = drinks[j]
+ groups[3].drink = drinks[l]
+ groups[4].drink = drinks[m]
+
+ assigndPet(groups)
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * 分配宠物
+ */
+fun assigndPet(groups: Array) {
+
+ for (i in pets.indices) {
+ for (j in pets.indices) {
+ if (i == j) continue
+ for (k in pets.indices) {
+ if (k == i || k == j) continue
+ for (l in pets.indices) {
+ if (l == k || l == j || l == i) continue
+ for (m in pets.indices) {
+ if (m == i || m == j || m == k || m == l) continue
+ groups[0].pet = pets[i]
+ groups[1].pet = pets[j]
+ groups[2].pet = pets[k]
+ groups[3].pet = pets[l]
+ groups[4].pet = pets[m]
+
+ assignedTabacco(groups)
+ }
+ }
+ }
+ }
+ }
+}
+
+fun assignedTabacco(groups: Array) {
+ for (i in tobaccos.indices) {
+ for (j in tobaccos.indices) {
+ if (i == j) continue
+ for (k in tobaccos.indices) {
+ if (k == i || k == j) continue
+ for (l in tobaccos.indices) {
+ if (l == k || l == j || l == i) continue
+ for (m in tobaccos.indices) {
+ if (m == i || m == j || m == k || m == l) continue
+ groups[0].tobacco = tobaccos[i]
+ groups[1].tobacco = tobaccos[j]
+ groups[2].tobacco = tobaccos[k]
+ groups[3].tobacco = tobaccos[l]
+ groups[4].tobacco = tobaccos[m]
+ DoGroupsfinalCheck(groups)
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ *
+ */
+
+
+fun DoGroupsfinalCheck(groups: Array) {
+// cnt++
+// println(cnt)
+
+ if (checkResult(groups)) {
+ PrintAllGroupsResult(groups)
+ println()
+ }
+}
+
+/**
+ *
+ *
+ * * (1)英国人住在红色的房子里
+(2)瑞典人养狗作为宠物
+(3)丹麦人喝茶
+(4)绿房子紧挨着白房子,在白房子的左边
+(5)绿房子的主人喝咖啡
+(6)抽 Pall Mall 牌香烟的人养鸟
+(7)黄色房子里的人抽 Dunhill 牌香烟
+
+
+(10)抽 Blends 牌香烟的人和养猫的人相邻
+(11)养马的人和抽 Dunhill 牌香烟的人相邻
+(12)抽 BlueMaster 牌香烟的人喝啤酒
+(13)德国人抽 Prince 牌香烟
+(14)挪威人和住在蓝房子的人相邻
+(15)抽 Blends 牌香烟的人和喝矿泉水的人相邻
+
+ */
+fun checkResult(groups: Array): Boolean {
+
+ for (i in groups.indices) {
+ var it = groups[i]
+ //(1)英国人住在红色的房子里
+ if (it.room_color == red) {
+ if (it.country != yingguo) {
+ return false
+ }
+ }
+
+ //(2)瑞典人养狗作为宠物
+ if (it.country == ruidian) {
+ if (it.pet != dog) {
+ return false
+ }
+ }
+
+ //(3)丹麦人喝茶
+ if (it.country == danmai) {
+ if (it.drink != tea) {
+ return false
+ }
+ }
+
+ //(5)绿房子的主人喝咖啡鸟
+ if (it.room_color == green) {
+ if (it.drink != coffee) {
+ return false
+ }
+ }
+
+ //(6)抽 Pall Mall 牌香烟的人养鸟
+ if (it.pet == bird) {
+ if (it.tobacco != PallMall) {
+ return false
+ }
+ }
+
+ //(7)黄色房子里的人抽 Dunhill 牌香烟
+ if (it.room_color == yellow) {
+ if (it.tobacco != Dunhill) {
+ return false
+ }
+ }
+
+ //(12)抽 BlueMaster 牌香烟的人喝啤酒
+ if (it.tobacco == BlueMaster) {
+ if (it.drink != beer) {
+ return false
+ }
+ }
+
+ //13 德国人抽 Prince 牌香烟
+ if (it.country == deguo) {
+ if (it.tobacco != Prince) {
+ return false
+ }
+ }
+
+
+ //(14)挪威人和住在蓝房子的人相邻
+ if (it.country == nuowei) {
+
+ var first = if ((i - 1) < 0) {
+ false
+ } else {
+ groups[i - 1].room_color == blue
+ }
+
+ var second = if ((i + 1) >= groups.size) {
+ false
+ } else {
+ groups[i + 1].room_color == blue
+ }
+ if (!first && !second) {
+ return false
+ }
+ }
+
+ // 15)抽 Blends 牌香烟的人和喝矿泉水的人相邻
+ if (it.tobacco == Blends) {
+
+ var first = if ((i - 1) < 0) {
+ false
+ } else {
+ groups[i - 1].drink == water
+ }
+
+ var second = if ((i + 1) >= groups.size) {
+ false
+ } else {
+ groups[i + 1].drink == water
+ }
+ if (!first && !second) {
+ return false
+ }
+ }
+
+ // (10)抽 Blends 牌香烟的人和养猫的人相邻
+ if (it.tobacco == Blends) {
+ var first = if ((i - 1) < 0) {
+ false
+ } else {
+ groups[i - 1].pet == cat
+ }
+
+ var second = if ((i + 1) >= groups.size) {
+ false
+ } else {
+ groups[i + 1].pet == cat
+ }
+ if (!first && !second) {
+ return false
+ }
+ }
+
+ //(11)养马的人和抽 Dunhill 牌香烟的人相邻
+ if (it.tobacco == Dunhill) {
+ var first = if ((i - 1) < 0) {
+ false
+ } else {
+ groups[i - 1].pet == horse
+ }
+
+ var second = if ((i + 1) >= groups.size) {
+ false
+ } else {
+ groups[i + 1].pet == horse
+ }
+ if (!first && !second) {
+ return false
+ }
+ }
+
+ //(4)绿房子紧挨着白房子,在白房子的左边
+ if ((i + 1) < groups.size) {
+ if (groups[i].room_color == green && groups[i + 1].room_color != white) {
+ return false
+ }
+ }
+
+ }
+
+ return true
+
+}
+
+/**
+ *
+ *
+国家 房子 宠物 饮料 香烟
+挪威 黄色 猫 矿泉水 Dunhill
+丹麦 蓝色 马 茶 Blends
+英国 红色 鸟 牛奶 PallMall
+德国 绿色 鱼 咖啡 Prince
+瑞典 白色 狗 啤酒 BlueMaster
+
+
+房间颜色:黄 国家:挪威 宠物:猫 饮料:水 抽烟:Dunhill
+房间颜色:蓝 国家:丹麦 宠物:马 饮料:茶 抽烟:Blends
+房间颜色:红 国家:英国 宠物:鸟 饮料:牛奶 抽烟:PallMall
+房间颜色:绿 国家:德国 宠物:鱼 饮料:咖啡 抽烟:Prince
+房间颜色:白 国家:瑞典 宠物:狗 饮料:啤酒 抽烟:BlueMaster
+ */
+fun PrintAllGroupsResult(groups: Array) {
+
+ groups.forEach {
+ print("房间颜色:${getColorName(it.room_color)} ")
+ print("国家:${getCountryName(it.country)} ")
+ print("宠物:${getPetName(it.pet)} ")
+ print("饮料:${getDrinkName(it.drink)} ")
+ println("抽烟:${getTabaccoName(it.tobacco)} ")
+ }
+}
+
+fun getColorName(room_color: Int): String {
+ return when (room_color) {
+ 1 -> "黄"
+ 2 -> "蓝"
+ 3 -> "红"
+ 4 -> "绿"
+ 5 -> "白"
+ else -> {
+ " "
+ }
+ }
+}
+
+fun getCountryName(room_color: Int): String {
+ return when (room_color) {
+ 1 -> "挪威"
+ 2 -> "丹麦"
+ 3 -> "英国"
+ 4 -> "德国"
+ 5 -> "瑞典"
+ else -> {
+ " "
+ }
+ }
+}
+
+fun getPetName(room_color: Int): String {
+ return when (room_color) {
+ 1 -> "猫"
+ 2 -> "马"
+ 3 -> "鸟"
+ 4 -> "鱼"
+ 5 -> "狗"
+ else -> {
+ " "
+ }
+ }
+}
+
+fun getDrinkName(room_color: Int): String {
+ return when (room_color) {
+ 1 -> "水"
+ 2 -> "茶"
+ 3 -> "牛奶"
+ 4 -> "咖啡"
+ 5 -> "啤酒"
+ else -> {
+ " "
+ }
+ }
+}
+
+
+fun getTabaccoName(room_color: Int): String {
+ return when (room_color) {
+ 1 -> "Dunhill"
+ 2 -> "Blends"
+ 3 -> "PallMall"
+ 4 -> "Prince"
+ 5 -> "BlueMaster"
+ else -> {
+ " "
+ }
+ }
+}
+
+/**
+ * 房子颜色 国籍 饮料 宠物 烟
+ */
+class Person_E(
+ var room_color: Int = -1,
+ var country: Int = -1,
+ var drink: Int = -1,
+ var pet: Int = -1,
+ var tobacco: Int = -1
+)
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionUpstairs.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionUpstairs.kt
new file mode 100644
index 0000000..96f9ea5
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionUpstairs.kt
@@ -0,0 +1,20 @@
+package com.wangpos.datastructure.algorithm
+
+/**
+ * 小明上楼梯有个习惯,就是一次要么走 1 级台阶,要么走 2 级台阶,有一个楼梯有 20 级台阶,问按照小明的习惯,他有多少种上楼梯的方法。
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+fun main() {
+
+
+
+}
+
+
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionbucket.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionbucket.kt
new file mode 100644
index 0000000..a66d892
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionbucket.kt
@@ -0,0 +1,180 @@
+package com.wangpos.datastructure.algorithm
+
+
+/**
+ * 8 5 3 分 4升水,一共有多少种分发
+ *
+ * 首先找到分析倒水有个动作,是谁到给了谁
+ *
+ * 然后我们穷举所有倒水可能,放到一个列表中
+ *
+ *
+ * 初始状态 8 0 0
+ * 当最终水的状态为 4 4 0 为止,
+ *
+ * 数据模型为了方便最查找,每个状态包含一个parent
+ *
+ * 我们针对已经遍历过的状态进行剪枝操作,否者会死循环
+ *
+ */
+fun main() {
+
+ var actions = arrayOf(
+ arrayOf(0, 1), arrayOf(0, 2), arrayOf(1, 0), arrayOf(1, 2), arrayOf(2, 0), arrayOf(2, 1)
+ )
+
+ var b8 = Bucket(8, 8)
+ var b5 = Bucket(0, 5)
+ var b3 = Bucket(0, 3)
+
+ var bucketState = BucketState(listOf(b8, b5, b3), 0, 0, null)
+
+ var stateInfos = mutableListOf()
+ stateInfos.add(bucketState)
+ search(stateInfos, bucketState, actions)
+
+ PrintResult(stateInfos)
+}
+
+/**
+ * 桶信息
+ */
+class Bucket(var water: Int, var capcity: Int)
+
+/**
+ * 求解一系列桶状态 序列
+ */
+class BucketState(
+ var buckets: List, var from: Int, var to: Int,
+ var parent: BucketState?
+) {
+ fun takeAction(i: Int, j: Int, next: (BucketState?) -> Unit) {
+
+ //穿件一个改变的实体
+ var newBucketState = copy()
+ newBucketState.parent = this
+
+ var fromBucket = newBucketState.buckets[i]
+ var toBucket = newBucketState.buckets[j]
+
+ if (fromBucket.water == 0) {
+ next(null)
+ return
+ }
+
+ var canAcceptWater = newBucketState.buckets[j].capcity - buckets[j].water
+
+ if (canAcceptWater == 0) {
+ next(null)
+ return
+ }
+
+ if (canAcceptWater <= fromBucket.water) {
+ toBucket.water = toBucket.capcity
+ fromBucket.water = fromBucket.water - canAcceptWater
+ } else {
+ toBucket.water = toBucket.water + fromBucket.water
+ fromBucket.water = 0
+ }
+
+ next(newBucketState)
+ }
+}
+
+/**
+ * 查找所有可能
+ */
+fun search(
+ states: MutableList,
+ bucketState: BucketState,
+ actions: Array>
+) {
+ if (IsFinalState(bucketState)) //判断是否到达[4,4,0]状态
+ {
+ println("找到了一种结果")
+ return
+ }
+ actions.forEach {
+ var next: BucketState? = null
+ //每次使用新的实体去查找,然后存储
+ bucketState.copy().takeAction(it[0], it[1]) {
+ next = it
+ }
+ next?.let {
+ if (!isDuplicate(states, it)) {
+ search(states, it, actions)
+ }
+ }
+ }
+}
+
+/**
+ * 是否之前已经操作出现了的状态避免重复
+ */
+fun isDuplicate(states: MutableList, next: BucketState): Boolean {
+
+ if (IsFinalState(next)) {
+ states.add(next)
+ return false
+ }
+ states.forEach {
+ if (it.buckets[0].water == next.buckets[0].water
+ && it.buckets[1].water == next.buckets[1].water
+ && it.buckets[2].water == next.buckets[2].water
+ ) {
+ return true
+ }
+ }
+ states.add(next)
+ return false
+}
+
+/**
+ * 打印结果
+ */
+fun PrintResult(states: List) {
+ for (i in states) {
+ if (IsFinalState(i)) {
+ printThree(i)
+ println("${i.from},${i.to} => ${printFormat(i)}")
+ println()
+ }
+ }
+}
+
+private fun printFormat(bucketState:BucketState):String {
+ return "" + bucketState.buckets[0].water + "-" + bucketState.buckets[1].water + "-" + bucketState.buckets[2].water
+}
+
+/**
+ * 打印树
+ */
+fun printThree(i: BucketState) {
+ i.parent?.let {
+ var result =
+ "" + it.buckets[0].water + "-" + it.buckets[1].water + "-" + it.buckets[2].water
+ printThree(it)
+ println("${it.from},${it.to} => " + result)
+ }
+
+}
+
+/**
+ * 满足 4 4 0
+ */
+fun IsFinalState(bucketState: BucketState): Boolean {
+ if (bucketState.buckets[0].water == 4 && bucketState.buckets[1].water == 4 && bucketState.buckets[2].water == 0) {
+ return true
+ }
+ return false
+}
+
+/**
+ * 复制新的实体
+ */
+fun BucketState.copy(): BucketState {
+ var b8 = Bucket(this.buckets[0].water, 8)
+ var b5 = Bucket(this.buckets[1].water, 5)
+ var b3 = Bucket(this.buckets[2].water, 3)
+ return BucketState(listOf(b8, b5, b3), from, to, parent)
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionchickenrabbit.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionchickenrabbit.kt
new file mode 100644
index 0000000..2fa1527
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/exhaustionchickenrabbit.kt
@@ -0,0 +1,25 @@
+package com.wangpos.datastructure.algorithm
+
+
+fun main(args: Array) {
+
+ chickenAndRabbit()
+}
+
+/**
+ * 鸡的解空间 0 50
+ *
+ * 兔的解空间 0 30
+ */
+fun chickenAndRabbit() {
+ for (rabbit in 0 until 31) {
+ var max = 50 - rabbit
+ for (chicken in 0 until max+1) {
+ var count = chicken * 2 + rabbit* 4
+
+ if (count == 120 && (chicken + rabbit)==50) {
+ println("鸡 $chicken 兔 $rabbit")
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/algorithm/wolfsheepfood.kt b/app/src/main/java/com/wangpos/datastructure/algorithm/wolfsheepfood.kt
new file mode 100644
index 0000000..7da659b
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/algorithm/wolfsheepfood.kt
@@ -0,0 +1,17 @@
+package com.wangpos.datastructure.algorithm
+
+fun main() {
+
+
+
+}
+
+
+
+class Wolf(left:Int,right:Int)
+
+class Food(left:Int,right:Int)
+
+class Sheep(left:Int,right:Int)
+
+class MoveRecord()
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/android/Intercept.kt b/app/src/main/java/com/wangpos/datastructure/android/Intercept.kt
new file mode 100644
index 0000000..3edba14
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/android/Intercept.kt
@@ -0,0 +1,60 @@
+package com.wangpos.datastructure.android
+
+import okhttp3.Interceptor
+
+abstract class Intercept {
+
+ open fun intercept(chain: Chain):Response?{
+ return chain.procced()
+ }
+}
+
+class Chain(val index: Int, val intercepts: List,val request: Request) {
+
+ fun procced(index: Int, intercepts: List, request: Request):Response? {
+ if (index < intercepts.size) {
+ val intercept = intercepts.get(index)
+ val next = Chain(index+1,intercepts,request)
+ val response = intercept.intercept(next)
+ return response
+ }
+
+ return null
+ }
+
+ fun procced():Response?{
+ return procced(index,intercepts,request)
+ }
+}
+
+class Response
+class Request(var url:String)
+
+/**
+ * 时间分发就是这样搞的
+ */
+class MyIntercept: Intercept() {
+ override fun intercept(chain: Chain): Response? {
+ return super.intercept(chain)
+ }
+}
+
+fun main() {
+
+ val intercepts = arrayListOf()
+
+ intercepts.add(object: Intercept() {
+ override fun intercept(chain: Chain): Response? {
+ chain.request.url = "123"
+ // 这里不会立即返回,需要等最后一个拦截器执行完,这是一个递归的操作,也可以直接 return null 或者想要的数据
+ return super.intercept(chain)
+ }
+
+ })
+ //添加很多拦截器
+ val request = Request("hahahah")
+ val chain = Chain(0, intercepts, request)
+ chain.procced(0, intercepts, request)
+}
+
+
diff --git a/app/src/main/java/com/wangpos/datastructure/graph/UndirectedGraph.java b/app/src/main/java/com/wangpos/datastructure/graph/UndirectedGraph.java
index 30631ec..5f696c7 100644
--- a/app/src/main/java/com/wangpos/datastructure/graph/UndirectedGraph.java
+++ b/app/src/main/java/com/wangpos/datastructure/graph/UndirectedGraph.java
@@ -145,8 +145,11 @@ public void DFS() {
}
-
-
+ /**
+ * 深度优先搜索
+ * @param i
+ * @param visited
+ */
private void DFS(int i, boolean[] visited) {
ENode node;
diff --git a/app/src/main/java/com/wangpos/datastructure/java/AddTwoNumber.java b/app/src/main/java/com/wangpos/datastructure/java/AddTwoNumber.java
index c9a3e24..d74f52f 100644
--- a/app/src/main/java/com/wangpos/datastructure/java/AddTwoNumber.java
+++ b/app/src/main/java/com/wangpos/datastructure/java/AddTwoNumber.java
@@ -4,6 +4,9 @@
import com.wangpos.datastructure.core.BaseActivity;
import java.util.ArrayList;
+import java.util.Collections;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
/**
* Created by qiyue on 2017/12/7.
@@ -54,7 +57,8 @@ protected String getSummaryData() {
public ListNode addTwoNumber(ListNode l1,ListNode l2){
-
+ CopyOnWriteArrayList list = new CopyOnWriteArrayList();
+ ConcurrentHashMap map = new ConcurrentHashMap(10);
return null;
}
diff --git a/app/src/main/java/com/wangpos/datastructure/java/JavaThreadActivity.java b/app/src/main/java/com/wangpos/datastructure/java/JavaThreadActivity.java
index 1e99025..19d770b 100644
--- a/app/src/main/java/com/wangpos/datastructure/java/JavaThreadActivity.java
+++ b/app/src/main/java/com/wangpos/datastructure/java/JavaThreadActivity.java
@@ -195,8 +195,8 @@ protected void onCreate(Bundle savedInstanceState) {
// t2.start();
- codeView2.showCode(" Person person = new Person(\"AAAAA\");\n" +
- " Person person2 = new Person(\"YYYYYY\");\n" +
+ codeView2.showCode(" Person_E person = new Person_E(\"AAAAA\");\n" +
+ " Person_E person2 = new Person_E(\"YYYYYY\");\n" +
" TestObjectLockThread t3 = new TestObjectLockThread(person);\n" +
" TestObjectLockThread t4 = new TestObjectLockThread(person2);\n" +
" t3.start();\n" +
diff --git a/app/src/main/java/com/wangpos/datastructure/java/condition/BoundedBuffer.kt b/app/src/main/java/com/wangpos/datastructure/java/condition/BoundedBuffer.kt
new file mode 100644
index 0000000..a912e0b
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/java/condition/BoundedBuffer.kt
@@ -0,0 +1,66 @@
+package com.wangpos.datastructure.java.condition
+
+import java.util.concurrent.ArrayBlockingQueue
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.locks.Lock
+import java.util.concurrent.locks.Condition
+import java.util.concurrent.locks.ReentrantLock
+import java.util.concurrent.locks.ReentrantReadWriteLock
+
+internal class BoundedBuffer {
+ val lock: Lock = ReentrantLock()
+ val notFull = lock.newCondition()
+ val notEmpty = lock.newCondition()
+
+ val items = arrayOfNulls(5)
+ var putptr: Int = 0
+ var takeptr: Int = 0
+ var count: Int = 0
+
+ @Throws(InterruptedException::class)
+ fun put(x: Any) {
+ lock.lock() //获取锁
+ try {
+ // 如果“缓冲已满”,则等待;直到“缓冲”不是满的,才将x添加到缓冲中。
+ while (count == items.size)
+ notFull.await()
+ // 将x添加到缓冲中
+ items[putptr] = x
+ // 将“put统计数putptr+1”;如果“缓冲已满”,则设putptr为0。
+ if (++putptr == items.size) putptr = 0
+ // 将“缓冲”数量+1
+ ++count
+ // 唤醒take线程,因为take线程通过notEmpty.await()等待
+ notEmpty.signal()
+
+ // 打印写入的数据
+ println(Thread.currentThread().name + " put " + x as Int)
+ } finally {
+ lock.unlock() // 释放锁
+ }
+ }
+
+ @Throws(InterruptedException::class)
+ fun take(): Any {
+ lock.lock() //获取锁
+ try {
+ // 如果“缓冲为空”,则等待;直到“缓冲”不为空,才将x从缓冲中取出。
+ while (count == 0)
+ notEmpty.await()
+ // 将x从缓冲中取出
+ val x = items[takeptr]
+ // 将“take统计数takeptr+1”;如果“缓冲为空”,则设takeptr为0。
+ if (++takeptr == items.size) takeptr = 0
+ // 将“缓冲”数量-1
+ --count
+ // 唤醒put线程,因为put线程通过notFull.await()等待
+ notFull.signal()
+
+ // 打印取出的数据
+ println(Thread.currentThread().name + " take " + x as Int)
+ return x
+ } finally {
+ lock.unlock() // 释放锁
+ }
+ }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/java/condition/ConditionDemo.kt b/app/src/main/java/com/wangpos/datastructure/java/condition/ConditionDemo.kt
new file mode 100644
index 0000000..33e16a7
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/java/condition/ConditionDemo.kt
@@ -0,0 +1,76 @@
+package com.wangpos.datastructure.java.condition
+
+import java.util.concurrent.locks.ReentrantLock
+
+
+
+val lock = ReentrantLock()
+val condition = lock.newCondition()
+
+
+private val bb = BoundedBuffer()
+
+fun main(args:Array){
+// var ta = ThreadA("A")
+//
+// lock.lock() // 获取锁
+// try {
+// println(Thread.currentThread().name + " start ta")
+// ta.start()
+//
+// println(Thread.currentThread().name + " block")
+// condition.await() // 等待 释放锁
+//
+// println(Thread.currentThread().name + " continue")
+// } catch (e: InterruptedException) {
+// e.printStackTrace()
+// } finally {
+// lock.unlock() // 释放锁
+// }
+
+
+ // 启动10个“写线程”,向BoundedBuffer中不断的写数据(写入0-9);
+ // 启动10个“读线程”,从BoundedBuffer中不断的读数据。
+ for (i in 0..9) {
+ PutThread("p$i", i).start()
+ TakeThread("t$i").start()
+ }
+
+
+}
+
+
+internal class PutThread(name: String, private val num: Int) : Thread(name) {
+ override fun run() {
+ try {
+ Thread.sleep(1) // 线程休眠1ms
+ bb.put(num) // 向BoundedBuffer中写入数据
+ } catch (e: InterruptedException) {
+ }
+
+ }
+}
+
+internal class TakeThread(name: String) : Thread(name) {
+ override fun run() {
+ try {
+ Thread.sleep(10) // 线程休眠1ms
+ val num = bb.take() as Int // 从BoundedBuffer中取出数据
+ } catch (e: InterruptedException) {
+ }
+
+ }
+}
+
+internal class ThreadA(name: String) : Thread(name) {
+
+ override fun run() {
+ lock.lock() // 获取锁
+ try {
+ println(Thread.currentThread().name + " wakup others")
+ condition.signal() // 唤醒“condition所在锁上的其它线程”
+ } finally {
+ lock.unlock() // 释放锁
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/java/condition/TestLinkBlockQueue.kt b/app/src/main/java/com/wangpos/datastructure/java/condition/TestLinkBlockQueue.kt
new file mode 100644
index 0000000..4927f20
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/java/condition/TestLinkBlockQueue.kt
@@ -0,0 +1,55 @@
+package com.wangpos.datastructure.java.condition
+
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.atomic.AtomicInteger
+import java.util.concurrent.locks.ReentrantLock
+import kotlin.concurrent.thread
+
+
+fun main() {
+
+
+ var blockingQueue = LinkedBlockingQueue(3)
+
+ var atomicoInteger = AtomicInteger();
+
+
+ var lock = ReentrantLock()
+ var condition = lock.newCondition()
+
+ var oneThread = thread {
+ // blockingQueue.put("test-$i")
+ var count = atomicoInteger.get()
+
+ lock.lock()
+ while (atomicoInteger.get() == 0) {
+ println("----------oneThread---------- ")
+ condition.await()
+ println("---------222-oneThread---------- ")
+ }
+ lock.unlock()
+ }
+
+ var threeThread = thread {
+ for (i in 1..12) {
+ println(">>>>>>>>threeThread>>>>>>>>> $i")
+
+ atomicoInteger.getAndIncrement()
+ }
+ condition.signal()
+ }
+
+/* var twoThread = thread {
+
+ // println("read = "+blockingQueue.take())
+ var count = atomicoInteger.get()
+ while (count > 10) {
+ for (i in 0..10) {
+ println(">>>>>>>>>>>>>>>>> $i")
+ atomicoInteger.getAndDecrement()
+ }
+ }
+ }*/
+ oneThread.start()
+ threeThread.start()
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/java/semaphore/TestSemaphore.kt b/app/src/main/java/com/wangpos/datastructure/java/semaphore/TestSemaphore.kt
new file mode 100644
index 0000000..5a11d7d
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/java/semaphore/TestSemaphore.kt
@@ -0,0 +1,7 @@
+package com.wangpos.datastructure.java.semaphore
+
+
+fun main() {
+
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/java/thread/Helper.kt b/app/src/main/java/com/wangpos/datastructure/java/thread/Helper.kt
new file mode 100644
index 0000000..cf36c03
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/java/thread/Helper.kt
@@ -0,0 +1,58 @@
+package com.wangpos.datastructure.java.thread
+
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
+
+/**
+ * Created by Edison Xu on 2017/3/2.
+ */
+enum class Helper {
+
+ instance;
+
+ fun run(r: Runnable) {
+ tPool.submit(r)
+ }
+
+ fun shutdown() {
+ tPool.shutdown()
+ }
+
+ companion object {
+
+ private val tPool = Executors.newFixedThreadPool(2)
+
+ fun buildNoArr(max: Int): Array {
+ val noArr = arrayOfNulls(max)
+ for (i in 0 until max) {
+ noArr[i] = Integer.toString(i + 1)
+ }
+ return noArr
+ }
+
+ fun buildCharArr(max: Int): Array {
+ val charArr = arrayOfNulls(max)
+ val tmp = 65
+ for (i in 0 until max) {
+ charArr[i] = (tmp + i).toChar().toString()
+ }
+ return charArr
+ }
+
+ @JvmStatic
+ fun printString(input: String) {
+ input?.let {
+ print(input)
+ }
+ }
+
+ @JvmStatic
+ fun print2String(input: String, input2: String) {
+ if (input == null)
+ return
+ print(input)
+ print(input2)
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/java/thread/ThreadCommunication.kt b/app/src/main/java/com/wangpos/datastructure/java/thread/ThreadCommunication.kt
new file mode 100644
index 0000000..c270c30
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/java/thread/ThreadCommunication.kt
@@ -0,0 +1,36 @@
+package com.wangpos.datastructure.java.thread
+
+import kotlin.concurrent.thread
+
+fun main() {
+
+ val messageBridge = MessageBridge()
+
+ thread(true) {
+ println(messageBridge.doSomeThing())
+ }
+ thread(true) {
+ println(messageBridge.doSomeThing2())
+
+ }
+
+}
+
+
+class MessageBridge {
+
+ var message: Int = 0
+
+ @Synchronized
+ fun doSomeThing(): Int {
+ message++
+ return message
+ }
+
+ @Synchronized
+ fun doSomeThing2(): Int {
+ message++
+ return message
+ }
+}
+
diff --git a/app/src/main/java/com/wangpos/datastructure/java/thread/ThreadCommunication2.kt b/app/src/main/java/com/wangpos/datastructure/java/thread/ThreadCommunication2.kt
new file mode 100644
index 0000000..62e59f8
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/java/thread/ThreadCommunication2.kt
@@ -0,0 +1,70 @@
+package com.wangpos.datastructure.java.thread
+
+import java.util.*
+
+
+fun main() {
+ val one = MethodOne()
+ Helper.instance.run(one.newThreadOne())
+ Helper.instance.run(one.newThreadTwo())
+ Helper.instance.shutdown()
+}
+
+/*8
+1. 第一种解法,包含多种小的不同实现方式,但一个共同点就是靠一个共享变量来做控制;
+a. 利用最基本的synchronized、notify、wait:
+ */
+
+
+
+class MethodOne {
+ private val threadToGo = ThreadToGo()
+
+ fun newThreadOne(): Runnable {
+ val inputArr = Helper.buildNoArr(52)
+ println(Arrays.toString(inputArr))
+ return Runnable {
+ try {
+ var i = 0
+ while (i < inputArr.size) {
+ synchronized(threadToGo) {
+ while (threadToGo.value == 2)
+ threadToGo.wait()
+ Helper.print2String(inputArr[i]!!, inputArr[i + 1]!!)
+ threadToGo.value = 2
+ threadToGo.notify()
+ }
+ i += 2
+ }
+ } catch (e: InterruptedException) {
+ println("Oops...")
+ }
+ }
+ }
+
+ fun newThreadTwo(): Runnable {
+ val inputArr = Helper.buildCharArr(26)
+ println(Arrays.toString(inputArr))
+ return Runnable {
+ try {
+ for (i in inputArr.indices) {
+ synchronized(threadToGo) {
+ while (threadToGo.value == 1)
+ threadToGo.wait()
+ Helper.printString(inputArr[i]!!)
+ threadToGo.value = 1
+ threadToGo.notify()
+ }
+ }
+ } catch (e: InterruptedException) {
+ println("Oops...")
+ }
+ }
+ }
+
+ internal inner class ThreadToGo:java.lang.Object() {
+ var value = 1
+ }
+
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/java/thread/automizationoperation.kt b/app/src/main/java/com/wangpos/datastructure/java/thread/automizationoperation.kt
new file mode 100644
index 0000000..dc3b682
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/java/thread/automizationoperation.kt
@@ -0,0 +1,49 @@
+package com.wangpos.datastructure.java.thread
+
+import java.util.*
+
+
+fun main() {
+ test()
+}
+
+fun test() {
+
+ var list = Vector()
+ for (i in 0..9999) {
+ list.add("string$i")
+ }
+
+ Thread(Runnable {
+ while (true) {
+ if (list.size > 0) {
+ val content = list.get(list.size - 1)
+ } else {
+ break
+ }
+ }
+ }).start()
+
+ Thread(Runnable {
+ while (true) {
+ if (list.size <= 0) {
+ break
+ }
+ list.removeAt(0)
+ try {
+ Thread.sleep(10)
+ } catch (e: InterruptedException) {
+ e.printStackTrace()
+ }
+
+ }
+ }).start()
+
+
+ /**
+ * Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9999
+ at java.util.Vector.get(Vector.java:748)
+ at com.wangpos.datastructure.java.thread.AutomizationoperationKt$test$1.run(automizationoperation.kt:23)
+ at java.lang.Thread.run(Thread.java:745)
+ */
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/leetcode/ArrayTest.kt b/app/src/main/java/com/wangpos/datastructure/leetcode/ArrayTest.kt
new file mode 100644
index 0000000..20e4d74
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/leetcode/ArrayTest.kt
@@ -0,0 +1,61 @@
+package com.wangpos.datastructure.leetcode
+
+
+/**
+ * 数组和字符串
+ *
+ * 数组的优缺点
+ * 能够在O(1)的情况查询一个元素
+ * 构建必须是连续的空间
+ * 删除和添加某一个元素必须遍历整个表O(n)
+ */
+fun main() {
+ println("hello World")
+
+ val data = "helloWorld"
+
+ val result = reverseString(data)
+ val result2 = reverseCharArray(data)
+ println(result)
+ println(result2)
+}
+
+/**
+ * 反转一个字符串
+ */
+fun reverseString(data: String): String {
+ var headerIndex = 0
+ var footerIndex = data.length - 1
+ val dataArray = data.toCharArray()
+
+ while (headerIndex != footerIndex && headerIndex < footerIndex) {
+ swap(headerIndex, footerIndex, dataArray)
+ headerIndex++
+ footerIndex--
+ }
+ val a = dataArray.toString()
+ var result = ""
+ for(i in 0 until dataArray.size){
+ result += dataArray[i]
+ }
+ return result
+}
+
+fun swap(headerIndex: Int, footerIndex: Int, dataArray: CharArray) {
+ val tempData = dataArray[footerIndex]
+ dataArray[footerIndex] = dataArray[headerIndex]
+ dataArray[headerIndex] = tempData
+}
+
+
+fun reverseCharArray(data: String):String {
+ val array = data.toCharArray()
+ var reverse = ""
+ for (i in array.size - 1 downTo 0) {
+ reverse += array[i]
+ }
+
+ return reverse
+}
+
+
diff --git a/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1.kt b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1.kt
new file mode 100644
index 0000000..772d021
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1.kt
@@ -0,0 +1,39 @@
+package com.wangpos.datastructure.leetcode
+
+import java.util.*
+
+
+/**
+ * 两数之和
+ *
+ * 暴力方法时间复杂度是O(n2)
+ *
+ * 也可以通过hash表降低查找时间,使其变成O(n),使用hash表注意给定数组中不能出现重复元素
+ */
+
+fun main() {
+ val nums = arrayOf(1, 2, 3, 4, 5, 6)
+ val target = 9
+ val resultArray = twoSum(nums, target)
+ println("结果:${Arrays.toString(resultArray)}")
+}
+
+/**
+ * 这种方法找不到所有的元素,只能找到一个,当存在里面有重复元素或不止一种情况
+ */
+fun twoSum(nums: Array, target: Int): IntArray {
+ // 一个hashMap存一个value 和position
+ val map = mutableMapOf()
+ for (i in 0 until nums.size) {
+ val targetData = target - nums[i]
+ if (map.containsKey(targetData)) {
+ val resultArray = IntArray(2)
+ resultArray[0] = map[targetData]!!
+ resultArray[1] = i
+ return resultArray
+ }
+ map.put(nums[i], i)
+ }
+ throw IllegalArgumentException("No two sum solution")
+}
+
diff --git a/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1038.kt b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1038.kt
new file mode 100644
index 0000000..52c09ab
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1038.kt
@@ -0,0 +1,100 @@
+package com.wangpos.datastructure.leetcode
+
+import java.util.*
+
+/**
+ * 二叉查找树(英语:Binary Search Tree),也称为 二叉搜索树、有序二叉树(Ordered Binary Tree)或排序二叉树(Sorted Binary Tree),是指一棵空树或者具有下列性质的二叉树:
+
+若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值;
+若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值;
+任意节点的左、右子树也分别为二叉查找树;
+没有键值相等的节点。
+二叉查找树相比于其他数据结构的优势在于查找、插入的时间复杂度较低。为 O(\log n)O(logn)。二叉查找树是基础性数据结构,用于构建更为抽象的数据结构,如集合、多重集、关联数组等。
+
+二叉查找树的查找过程和次优二叉树类似,通常采取二叉链表作为二叉查找树的存储结构。中序遍历二叉查找树可得到一个关键字的有序序列,一个无序序列可以通过构造一棵二叉查找树变成一个有序序列,构造树的过程即为对无序序列进行查找的过程。每次插入的新的结点都是二叉查找树上新的叶子结点,在进行插入操作时,不必移动其它结点,只需改动某个结点的指针,由空变为非空即可。搜索、插入、删除的复杂度等于树高,期望 O(\log n)O(logn),最坏 O(n)O(n)(数列有序,树退化成线性表)。
+
+
+
+虽然二叉查找树的最坏效率是 O(n)O(n),但它支持动态查询,且有很多改进版的二叉查找树可以使树高为 O(\log n)O(logn),从而将最坏效率降至 O(\log n)O(logn),如 AVL 树、红黑树等。
+
+ */
+fun main() {
+
+ //右左根的遍历方式
+ //记忆搜索
+
+ //不存在相等的元素
+ val arrayNode = arrayOf(4, 1, 6, 0, 2, 5, 7, null, null, null, 3, null, null, null, 8)
+// val arrayNode = arrayOf( 6, 5, 7, 8)
+ var head: TreeNode? = null
+ arrayNode.forEach {
+ if (it != null) {
+ if (head == null) {
+ head = TreeNode(it)
+ } else {
+ createBinearySearchTree(head!!, it!!)
+ }
+ }
+ }
+ //打出中序遍历结果判断访问是否正确
+ head?.let { printNode(it) }
+
+ println()
+ head?.let { modifyNode(it) }
+ println()
+
+
+ println()
+ head?.let { printNode(it) }
+
+}
+
+fun createBinearySearchTree(head: TreeNode, it: Int) {
+
+ var next: TreeNode? = null
+ if (it > head.`val`) {
+ next = head.right
+ if (next == null) {
+ head.right = TreeNode(it)
+ return
+ }
+ } else {
+ next = head.left
+ if (next == null) {
+ head.left = TreeNode(it)
+ return
+ }
+ }
+
+ createBinearySearchTree(next, it)
+
+}
+
+//中序遍历左跟右
+fun printNode(head: TreeNode) {
+ head.left?.let { printNode(it) }
+ print(" ${head.`val`} ")
+ head.right?.let { printNode(it) }
+}
+
+
+
+var cacheTotal = 0
+//右 根 左 把每个节点和队列之前的计算和添加到队列,
+fun modifyNode(root: TreeNode) {
+ root.right?.let { modifyNode(it) }
+ print(" ${root.`val`} ")
+ if (cacheTotal==0) {
+ cacheTotal = root.`val`
+
+ } else {
+ cacheTotal += root.`val`
+ root.`val` = cacheTotal
+ }
+ root.left?.let { modifyNode(it) }
+}
+
+class TreeNode(var `val`: Int) {
+ var left: TreeNode? = null
+ var right: TreeNode? = null
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1203.java b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1203.java
new file mode 100644
index 0000000..8954932
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1203.java
@@ -0,0 +1,246 @@
+package com.wangpos.datastructure.leetcode;
+
+import android.support.annotation.NonNull;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Queue;
+
+/**
+ *
+ * 项目之间的依赖关系,用拓扑排序解决。这比较明显。
+ *
+ * 难点在于怎么理解“ 同一小组的项目,排序后在列表中彼此相邻 ”。
+ *
+ *
+ * 这个题通过提示可以知道使用两层拓扑排序,但是坑还是挺多的。
+ * 1.需要给单独的项目创建一个组
+ * 2.需要通过项目ID找到关联的组,同时需要维护组本身的序列
+ * 一开始想图省事,用一个group[]表示,后来发现这样有耦合问题。改用List维护组本身,用数组维护项目到组的映射关系,初始化List为m个,如果遇到单独的项目,
+ * 则把当前List大小设置为组ID分配给这个项目。通过这个解决了项目ID和组ID耦合的问题。
+ *
+ */
+public class LeetCode1203 {
+
+ public static void main(String args[]) {
+ int[] group = new int[]{-1, -1, 1, 0, 0, 1, 0, -1};
+ int n = 8;
+ int m = 2;
+ List> beforeItems = new ArrayList<>();
+ //[[],[6],[5],[6],[3,6],[],[],[]]
+ beforeItems.add(createItem());
+ beforeItems.add(createItem());
+ beforeItems.get(beforeItems.size() - 1).add(6);
+ beforeItems.add(createItem());
+ beforeItems.get(beforeItems.size() - 1).add(5);
+ beforeItems.add(createItem());
+ beforeItems.get(beforeItems.size() - 1).add(6);
+ beforeItems.add(createItem());
+ beforeItems.get(beforeItems.size() - 1).add(3);
+ beforeItems.get(beforeItems.size() - 1).add(6);
+ beforeItems.add(createItem());
+ beforeItems.add(createItem());
+ beforeItems.add(createItem());
+
+ int[] result = new LeetCode1203().sortItems(8, 2, group, beforeItems);
+ System.out.println(Arrays.toString(result));
+
+ }
+
+ @NonNull
+ private static List createItem() {
+ return new ArrayList();
+ }
+
+
+ Listqueue = new LinkedList<>();
+
+
+ //项目
+ static class Item {
+ //项目id
+ int id;
+
+ //初始化入度
+ int inputCnt;
+ //下一个项目
+ List nextItems = new ArrayList<>();
+
+ Item(int id) {
+ this.id = id;
+ }
+ }
+
+ //组
+ static class Group {
+ //组id
+ int id;
+
+ //入度
+ int inputCnt;
+
+ List items = new ArrayList<>();
+ //下一个 组
+ List nextGroups = new ArrayList<>();
+
+ Group(int id) {
+ this.id = id;
+ }
+ }
+
+ /**
+ * 使用邻接表的形式
+ * @param n
+ * @param m
+ * @param group
+ * @param beforeItems
+ * @return
+ */
+ public int[] sortItems(int n, int m, int[] group, List> beforeItems) {
+ //项目数组
+ Item[] items = new Item[n];
+
+ //用来保存已经绑定过item的group数组
+ Group[] itemToGroup = new Group[n];
+
+ //组
+ List oriGroups = new ArrayList<>();
+
+ //初始化组种类
+ for (int j = 0; j < m; j++) {
+ oriGroups.add(new Group(j));
+ }
+
+ //初始化项目
+ for (int i = 0; i < n; i++) {
+ items[i] = new Item(i);
+ }
+
+ /**
+ * 遍历每个项目,所属组
+ */
+ for (int i = 0; i < group.length; i++) {
+ int groupId = group[i];
+ if (groupId == -1) {// 项目不属于任何组
+ //创建一个新组
+ Group temp = new Group(oriGroups.size());
+ //保存到组列表
+ oriGroups.add(temp);
+ //组绑定这个项目,因为项目是按顺序的所以i就是这个项目
+ temp.items.add(i);
+ itemToGroup[i] = temp;
+ } else {
+ //根据组id 绑定项目
+ oriGroups.get(groupId).items.add(i);
+ itemToGroup[i] = oriGroups.get(groupId);
+ }
+ }
+
+ for (int i = 0; i < beforeItems.size(); i++) {
+ List array = beforeItems.get(i);
+ //初始化入度
+ items[i].inputCnt = array.size();
+ for (Integer itemId : array) {
+ //每个项目的下一个项目
+ items[itemId].nextItems.add(i);
+ //获取绑定项目后的组
+ Group beforeGroup = itemToGroup[itemId];
+ //当前组
+ Group curGroup = itemToGroup[i];
+ if (beforeGroup != curGroup) {
+ //前一个组保存他的下一个组
+ beforeGroup.nextGroups.add(curGroup);
+ //当前组入度多1
+ curGroup.inputCnt++;
+ }
+ }
+ }
+
+ Queue groupQueue = new LinkedList<>();
+
+ //找到入度为0的组添加到待遍历的队列中
+ for (Group ele : oriGroups) {
+ if (ele.inputCnt == 0) {
+ groupQueue.offer(ele);
+ }
+ }
+
+ if (groupQueue.isEmpty()) {
+ return new int[0];
+ }
+
+ int[] result = new int[n];
+ int resultIndex = 0;
+ while (!groupQueue.isEmpty()) {
+ int size = groupQueue.size();
+ for (int i = 0; i < size; i++) {
+ Group curGroup = groupQueue.poll();
+ Queue itemQueue = new LinkedList<>();
+ if (curGroup.items.isEmpty()) {
+ continue;
+ }
+
+ //再进行item拓扑排序
+ for (int temp : curGroup.items) {
+ if (items[temp].inputCnt == 0) {
+ itemQueue.offer(temp);
+ }
+ }
+
+ if (itemQueue.isEmpty()) {
+ return new int[0];
+ }
+
+ //
+ while (!itemQueue.isEmpty()) {
+ int itemQueueSize = itemQueue.size();
+ for (int j = 0; j < itemQueueSize; j++) {
+ Integer itemId = itemQueue.poll();
+ //保存结果
+ result[resultIndex++] = itemId;
+ //遍历下一个
+ for (int nextItemId : items[itemId].nextItems) {
+ items[nextItemId].inputCnt--;
+ if (items[nextItemId].inputCnt == 0 && curGroup.items.contains(nextItemId)) {
+ itemQueue.offer(nextItemId);
+ }
+ }
+ }
+ }
+
+ //项目中存在环
+ for (int itemId : curGroup.items) {
+ if (items[itemId].inputCnt > 0) {
+ return new int[0];
+ }
+ }
+
+ //遍历下一个组
+ for (Group nextGroup : curGroup.nextGroups) {
+ nextGroup.inputCnt--;
+ if (nextGroup.inputCnt == 0) {
+ groupQueue.offer(nextGroup);
+ }
+ }
+ }
+ }
+ //组中存在环
+ for (Group ele : oriGroups) {
+ if (ele.inputCnt > 0) {
+ return new int[0];
+ }
+ }
+
+ for (int k = 0; k < items.length; k++) {
+ if (items[k].inputCnt > 0) {
+ return new int[0];
+ }
+ }
+
+ return result;
+ }
+
+
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1214.java b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1214.java
new file mode 100644
index 0000000..65e3b74
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1214.java
@@ -0,0 +1,101 @@
+package com.wangpos.datastructure.leetcode;
+
+import java.util.Stack;
+
+public class LeetCode1214 {
+
+ public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) {
+
+ Stack stack1 = new Stack<>();
+ Stack stack2 = new Stack<>();
+ searchRoot11(root1, stack1);
+ searchRoot22(root2, stack2);
+ int t = 0;
+ int small = stack1.pop();
+ int large = stack2.pop();
+ while (!stack1.empty() || !stack2.empty()) {
+ t = small + large;
+ if (t == target) {
+ return true;
+ } else if (t > target) {
+ // 取较小的
+ if(!stack1.empty()) {
+ small = stack1.pop();
+ }else{
+ break;
+ }
+ } else {
+ // 取较大的
+ if(!stack2.empty()) {
+ large = stack2.pop();
+ }else{
+ break;
+ }
+ }
+ }
+ return false;
+ }
+
+ private void searchRoot11(TreeNode root1, Stack stack) {
+ if (root1 == null) {
+ return;
+ }
+ searchRoot11(root1.getLeft(), stack);
+ stack.add(root1.getVal());
+ searchRoot11(root1.getRight(), stack);
+ }
+
+ private void searchRoot22(TreeNode root1, Stack stack) {
+
+ if (root1 == null) {
+ return;
+ }
+ searchRoot22(root1.getRight(), stack);
+ stack.add(root1.getVal());
+ searchRoot22(root1.getLeft(), stack);
+ }
+//
+// fun twoSumBSTs2(root1: TreeNode?, root2: TreeNode?, target: Int): Boolean {
+//
+// val stack1 = Stack()//从小到大 top最大
+// val stack2 = Stack()//从大到小
+// searchRoot11(root1, stack1)
+// searchRoot22(root2, stack2)
+// var t = 0
+// var small = stack1.pop()
+// var large = stack2.pop()
+// while (stack1.isNotEmpty() && stack2.isNotEmpty()) {
+// t = small + large
+// println(small)
+// println(large)
+// if (t == target) {
+// return true
+// } else if (t > target) {
+// // 取较小的
+// small = stack1.pop()
+// } else {
+// // 取较大的
+// large = stack2.pop()
+// }
+// }
+// return false
+// }
+//
+// fun searchRoot11(root1: TreeNode?, stack: Stack) {
+// if (root1 == null) {
+// return
+// }
+// searchRoot11(root1.left, stack)
+// stack.add(root1.`val`)
+// searchRoot11(root1.right, stack)
+// }
+//
+// fun searchRoot22(root2: TreeNode?, stack: Stack) {
+// if (root2 == null) {
+// return
+// }
+// searchRoot22(root2.right, stack)
+// stack.add(root2.`val`)
+// searchRoot22(root2.left, stack)
+// }
+}
diff --git a/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1214.kt b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1214.kt
new file mode 100644
index 0000000..8cbc305
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1214.kt
@@ -0,0 +1,138 @@
+package com.wangpos.datastructure.leetcode
+
+import java.util.*
+
+fun main() {
+
+ val root1Array = arrayOf(0, -10, 10)
+
+ val root2Array = arrayOf(5, 1, 7, 0, 2)
+
+ val target = 18
+
+ var root1: TreeNode? = null
+ var root2: TreeNode? = null
+ root1Array.forEach {
+ if (it != null) {
+ if (root1 == null) {
+ root1 = TreeNode(it)
+ } else {
+ createBinearySearchTree(root1!!, it!!)
+ }
+ }
+ }
+
+ root2Array.forEach {
+ if (it != null) {
+ if (root2 == null) {
+ root2 = TreeNode(it)
+ } else {
+ createBinearySearchTree(root2!!, it!!)
+ }
+ }
+ }
+
+// root1?.let { printNode(it) }
+// println()
+// root2?.let { printNode(it) }
+
+// val result = twoSumBSTs(root1, root2, target)
+
+// val result = twoSumBSTs2(root1, root2, target)
+ val result = LeetCode1214().twoSumBSTs(root1,root2,target);
+ println("结果:${result}")
+}
+
+/**
+ * 这种双层嵌套效率比较低,中序遍历时间复杂度是O(n) 后面的查找属于也是中序遍历所以O(n*n)
+ *
+ */
+fun twoSumBSTs(root1: TreeNode?, root2: TreeNode?, target: Int): Boolean {
+ searchRoot1(root1, root2, target)
+ return searchResult
+}
+
+fun searchRoot1(root1: TreeNode?, root2: TreeNode?, target: Int) {
+
+ if (root1 == null || searchResult) {
+ return
+ }
+ searchRoot1(root1?.left, root2, target)
+ if (root1.`val` > target) {
+ return
+ }
+ searchRoot2(root2, target - root1.`val`)
+ searchRoot1(root1?.right, root2, target)
+}
+
+var searchResult = false
+fun searchRoot2(root2: TreeNode?, i: Int) {
+ if (root2 == null || searchResult) {
+ return
+ }
+ searchRoot2(root2.left, i)
+ if (root2.`val` == i) {
+ searchResult = true
+ return
+ }
+ if (root2.`val` > i) {
+ return
+ }
+ searchRoot2(root2.right, i)
+}
+
+/**
+ * 将两个树进行中序遍历,和逆向中序,时间复杂度 O(n)*2
+ * 然后放入两个栈中,得到两个一个从小到大,一个从大到小的
+ *
+ * 然后遍历两个栈,如果相加之和小于t,就从最小的栈去继续找,反之从大的栈中找
+ *
+ *
+ */
+fun twoSumBSTs2(root1: TreeNode?, root2: TreeNode?, target: Int): Boolean {
+
+ val stack1 = Stack()//从小到大 top最大
+ val stack2 = Stack()//从大到小
+ searchRoot11(root1, stack1)
+ searchRoot22(root2, stack2)
+ var t = 0
+ var small = stack1.pop()
+ var large = stack2.pop()
+ while (stack1.isNotEmpty() || stack2.isNotEmpty()) {
+ t = small + large
+ println(small)
+ println(large)
+ if (t == target) {
+ return true
+ } else if (t > target) {
+ // 取较小的
+ if(stack1.isNotEmpty()) {
+ small = stack1.pop()
+ }
+ } else {
+ // 取较大的
+ if(stack1.isNotEmpty()) {
+ large = stack2.pop()
+ }
+ }
+ }
+ return false
+}
+
+fun searchRoot11(root1: TreeNode?, stack: Stack) {
+ if (root1 == null) {
+ return
+ }
+ searchRoot11(root1.left, stack)
+ stack.add(root1.`val`)
+ searchRoot11(root1.right, stack)
+}
+
+fun searchRoot22(root2: TreeNode?, stack: Stack) {
+ if (root2 == null) {
+ return
+ }
+ searchRoot22(root2.right, stack)
+ stack.add(root2.`val`)
+ searchRoot22(root2.left, stack)
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1272.java b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1272.java
new file mode 100644
index 0000000..cf64245
--- /dev/null
+++ b/app/src/main/java/com/wangpos/datastructure/leetcode/LeetCode1272.java
@@ -0,0 +1,139 @@
+package com.wangpos.datastructure.leetcode;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * 给你一个 有序的 不相交区间列表 intervals 和一个要删除的区间 toBeRemoved, intervals 中的每一个区间 intervals[i] = [a, b] 都表示满足 a <= x < b 的所有实数 x 的集合。
+ *
+ * 我们将 intervals 中任意区间与 toBeRemoved 有交集的部分都删除。
+ *
+ * 返回删除所有交集区间后, intervals 剩余部分的 有序 列表。
+ *
+ *
+ * 示例 1:
+ *
+ * 输入:intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
+ * 输出:[[0,1],[6,7]]
+ * 示例 2:
+ *
+ * 输入:intervals = [[0,5]], toBeRemoved = [2,3]
+ * 输出:[[0,2],[3,5]]
+ *
+ */
+public class LeetCode1272 {
+
+ public static void main(String[] args) {
+ LeetCode1272 testObject = new LeetCode1272();
+// int[][] nums = new int[][]{new int[]{3, 4}, new int[]{0, 3}, new int[]{0, 2}, new int[]{5, 7}};
+// int[] toBeRemoved = new int[]{1, 6};
+
+// int[][] nums = new int[][]{new int[]{0, 5}};
+// int[] toBeRemoved = new int[]{2, 3};
+
+// int[][] nums = new int[][]{new int[]{-5, -4}, new int[]{-3, -2}, new int[]{1, 2}, new int[]{3, 5},new int[]{8,9}};
+// int[] toBeRemoved = new int[]{-1, 4};
+
+ int[][] nums = new int[][]{new int[]{0, 100}};
+ int[] toBeRemoved = new int[]{0, 50};
+ testObject.removeInterval(nums, toBeRemoved);
+ }
+
+ public List> removeInterval(int[][] intervals, int[] toBeRemoved) {
+
+ //排序分别比较两个条件,按顺序比较
+ sortArray(intervals, new int[]{0, 1});
+
+ /**
+ *
+ * 0 2 0 3 3 4 5 7
+ * 1 6
+ *
+ * 0 1 6 7
+ *
+ */
+
+
+ List> result = new ArrayList<>();
+ int[] lastSaveArray = null;
+ for (int[] interval : intervals) {
+ if (interval[0] <= toBeRemoved[0]) {
+ if (interval[1] > toBeRemoved[0]) {
+ //修改 入队列
+
+ int backupDataRight = interval[1];
+ if (interval[0] != toBeRemoved[0]) {
+ interval[1] = toBeRemoved[0];
+
+ if (lastSaveArray == null) {
+ lastSaveArray = saveResult(result, interval);
+ } else if (lastSaveArray[0] == interval[0] && lastSaveArray[1] == interval[1]) {
+ continue;
+ } else {
+ lastSaveArray = saveResult(result, interval);
+ }
+
+ }
+
+ if (backupDataRight >= toBeRemoved[1]) {
+ int newArray[] = new int[]{toBeRemoved[1], backupDataRight};
+ lastSaveArray = saveResult(result, newArray);
+ }
+
+ } else {
+ lastSaveArray = saveResult(result, interval);
+ }
+ } else {
+ // 8 9 -1 4
+ //
+ if (interval[1] <= toBeRemoved[1]) {
+ // 8 9 1 10
+ //重复空间
+// lastSaveArray = saveResult(result, interval);
+ } else {
+ if (interval[0] <= toBeRemoved[1]) {
+ interval[0] = toBeRemoved[1];
+ }
+ lastSaveArray = saveResult(result, interval);
+ }
+ }
+ }
+
+
+ return result;
+ }
+
+ private int[] saveResult(List> result, int[] interval) {
+ int[] lastSaveArray;
+ lastSaveArray = interval;
+ List cell = new ArrayList();
+ cell.add(interval[0]);
+ cell.add(interval[1]);
+ result.add(cell);
+ return lastSaveArray;
+ }
+
+ private void sortArray(int[][] intervals, final int[] order) {
+ Arrays.sort(intervals, new Comparator