diff --git a/README.md b/README.md index 8d6bb47..916e80b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ ## learn-java example of learn java +algorithm has moved to [learn-algorithm](https://github.com/wcong/learn-algorithm) + diff --git a/pom.xml b/pom.xml index b4466ad..5f4edf1 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ junit junit - 3.8.1 + 4.13.1 test @@ -206,6 +206,11 @@ jackson-annotations 2.3.3 + + io.reactivex.rxjava2 + rxjava + 2.1.6 + org.freemarker freemarker diff --git a/src/main/java/org/wcong/App.java b/src/main/java/org/wcong/App.java index 49e6332..da1598c 100644 --- a/src/main/java/org/wcong/App.java +++ b/src/main/java/org/wcong/App.java @@ -1,255 +1,398 @@ package org.wcong; -import java.lang.reflect.ParameterizedType; -import java.math.BigDecimal; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; +import org.wcong.test.hackerrank.string.PerfectString; + +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Scanner; /** * Hello world! */ public class App { - static int a; - - public static void main(String[] args) { - System.out.println(3/2); - } - - public static Class findSuperClassParameterType(Object instance, int parameterIndex) { - Class subClass = instance.getClass(); - while (subClass != subClass.getSuperclass()) { - // instance.getClass() is no subclass of classOfInterest or instance is a direct instance of classOfInterest - subClass = subClass.getSuperclass(); - if (subClass == null) throw new IllegalArgumentException(); - } - ParameterizedType parameterizedType = (ParameterizedType) subClass.getGenericSuperclass(); - return (Class) parameterizedType.getActualTypeArguments()[parameterIndex]; - } - - public class A { - } - - public static class B { - } - - - public enum LogisticsCompanyEnum { - - QITA("Q", 0, "其它"), SHUNFENG("S", 1, "顺丰速运"), ZHONGTONG("Z", 2, "中通快递"), SHENTONG("S", 3, "申通快递"), YUANTONG("Y", 4, "圆通快递"), YUNDA("Y", 5, "韵达快递"), - EMS("E", 6, "EMS"), TIANTIAN("T", 7, "天天快递"), GUOTONG("G", 8, "国通快递"), SUER("S", 9, "速尔快递"), BAISHI("B", 10, "百世汇通"), LIANBANG("L", 11, "联邦快递"), - QUANFENG("Q", 12, "全峰快递"), ZAIJISONG("Z", 13, "宅急送"), QUANYI("Q", 14, "全一快递"), UPS("U", 15, "UPS快递"), - ZHONG_WAI_YUN("Z", 16, "中外运速递"),; - - private String initial; - private int logisticsCompanyId; - private String logisticsCompanyName; - - private LogisticsCompanyEnum(String initial, int logisticsCompanyId, String logisticsCompanyName) { - this.initial = initial; - this.logisticsCompanyId = logisticsCompanyId; - this.logisticsCompanyName = logisticsCompanyName; - } - - public String getInitial() { - return initial; - } - - public int getLogisticsCompanyId() { - return logisticsCompanyId; - } - - public String getLogisticsCompanyName() { - return logisticsCompanyName; - } - - } - - private static final Map ID_TO_NAME_LOGISTICS = new HashMap(); - - static { - ID_TO_NAME_LOGISTICS.put(16L, "中外运速递"); - ID_TO_NAME_LOGISTICS.put(17L, "E特快"); - ID_TO_NAME_LOGISTICS.put(18L, "芝麻开门"); - ID_TO_NAME_LOGISTICS.put(19L, "赛澳递"); - ID_TO_NAME_LOGISTICS.put(20L, "安能物流"); - ID_TO_NAME_LOGISTICS.put(21L, "安迅物流"); - ID_TO_NAME_LOGISTICS.put(22L, "巴伦支快递"); - ID_TO_NAME_LOGISTICS.put(23L, "北青小红帽"); - ID_TO_NAME_LOGISTICS.put(24L, "百福东方物流"); - ID_TO_NAME_LOGISTICS.put(25L, "邦送物流"); - ID_TO_NAME_LOGISTICS.put(26L, "宝凯物流"); - ID_TO_NAME_LOGISTICS.put(27L, "百千诚物流"); - ID_TO_NAME_LOGISTICS.put(28L, "博源恒通"); - ID_TO_NAME_LOGISTICS.put(29L, "百成大达物流"); - ID_TO_NAME_LOGISTICS.put(30L, "百世快运"); - ID_TO_NAME_LOGISTICS.put(31L, "COE(东方快递)"); - ID_TO_NAME_LOGISTICS.put(32L, "城市100"); - ID_TO_NAME_LOGISTICS.put(33L, "传喜物流"); - ID_TO_NAME_LOGISTICS.put(34L, "城际速递"); - ID_TO_NAME_LOGISTICS.put(35L, "成都立即送"); - ID_TO_NAME_LOGISTICS.put(36L, "出口易"); - ID_TO_NAME_LOGISTICS.put(37L, "晟邦物流"); - ID_TO_NAME_LOGISTICS.put(38L, "DHL快递"); - ID_TO_NAME_LOGISTICS.put(39L, "DHL"); - ID_TO_NAME_LOGISTICS.put(40L, "德邦大田物流"); - ID_TO_NAME_LOGISTICS.put(41L, "东方快递"); - ID_TO_NAME_LOGISTICS.put(42L, "递四方"); - ID_TO_NAME_LOGISTICS.put(43L, "大洋物流"); - ID_TO_NAME_LOGISTICS.put(44L, "店通快递"); - ID_TO_NAME_LOGISTICS.put(45L, "德创物流"); - ID_TO_NAME_LOGISTICS.put(46L, "东红物流"); - ID_TO_NAME_LOGISTICS.put(47L, "D速物流"); - ID_TO_NAME_LOGISTICS.put(48L, "东瀚物流"); - ID_TO_NAME_LOGISTICS.put(49L, "达方物流"); - ID_TO_NAME_LOGISTICS.put(50L, "俄顺达"); - ID_TO_NAME_LOGISTICS.put(51L, "FedEx快递"); - ID_TO_NAME_LOGISTICS.put(52L, "飞康达物流"); - ID_TO_NAME_LOGISTICS.put(53L, "飞豹快递"); - ID_TO_NAME_LOGISTICS.put(54L, "飞狐快递"); - ID_TO_NAME_LOGISTICS.put(55L, "凡宇速递"); - ID_TO_NAME_LOGISTICS.put(56L, "颿达国际"); - ID_TO_NAME_LOGISTICS.put(57L, "飞远配送"); - ID_TO_NAME_LOGISTICS.put(58L, "飞鹰物流"); - ID_TO_NAME_LOGISTICS.put(59L, "风行天下"); - ID_TO_NAME_LOGISTICS.put(60L, "GATI快递"); - ID_TO_NAME_LOGISTICS.put(61L, "港中能达物流"); - ID_TO_NAME_LOGISTICS.put(62L, "共速达"); - ID_TO_NAME_LOGISTICS.put(63L, "广通速递"); - ID_TO_NAME_LOGISTICS.put(64L, "广东速腾物流"); - ID_TO_NAME_LOGISTICS.put(65L, "港快速递"); - ID_TO_NAME_LOGISTICS.put(66L, "高铁速递"); - ID_TO_NAME_LOGISTICS.put(67L, "冠达快递"); - ID_TO_NAME_LOGISTICS.put(68L, "华宇物流"); - ID_TO_NAME_LOGISTICS.put(69L, "恒路物流"); - ID_TO_NAME_LOGISTICS.put(70L, "好来运快递"); - ID_TO_NAME_LOGISTICS.put(71L, "华夏龙物流"); - ID_TO_NAME_LOGISTICS.put(72L, "海航天天"); - ID_TO_NAME_LOGISTICS.put(73L, "河北建华"); - ID_TO_NAME_LOGISTICS.put(74L, "海盟速递"); - ID_TO_NAME_LOGISTICS.put(75L, "华企快运"); - ID_TO_NAME_LOGISTICS.put(76L, "昊盛物流"); - ID_TO_NAME_LOGISTICS.put(77L, "户通物流"); - ID_TO_NAME_LOGISTICS.put(78L, "华航快递"); - ID_TO_NAME_LOGISTICS.put(79L, "黄马甲快递"); - ID_TO_NAME_LOGISTICS.put(80L, "合众速递(UCS)"); - ID_TO_NAME_LOGISTICS.put(81L, "韩润物流"); - ID_TO_NAME_LOGISTICS.put(82L, "皇家物流"); - ID_TO_NAME_LOGISTICS.put(83L, "伙伴物流"); - ID_TO_NAME_LOGISTICS.put(84L, "红马速递"); - ID_TO_NAME_LOGISTICS.put(85L, "汇文配送"); - ID_TO_NAME_LOGISTICS.put(86L, "华赫物流"); - ID_TO_NAME_LOGISTICS.put(87L, "佳吉物流"); - ID_TO_NAME_LOGISTICS.put(88L, "佳怡物流"); - ID_TO_NAME_LOGISTICS.put(89L, "加运美快递"); - ID_TO_NAME_LOGISTICS.put(90L, "急先达物流"); - ID_TO_NAME_LOGISTICS.put(91L, "京广速递"); - ID_TO_NAME_LOGISTICS.put(92L, "晋越快递"); - ID_TO_NAME_LOGISTICS.put(93L, "捷特快递"); - ID_TO_NAME_LOGISTICS.put(94L, "久易快递"); - ID_TO_NAME_LOGISTICS.put(95L, "快捷快递"); - ID_TO_NAME_LOGISTICS.put(96L, "康力物流"); - ID_TO_NAME_LOGISTICS.put(97L, "跨越速运"); - ID_TO_NAME_LOGISTICS.put(98L, "快优达速递"); - ID_TO_NAME_LOGISTICS.put(99L, "快淘快递"); - ID_TO_NAME_LOGISTICS.put(100L, "联昊通物流"); - ID_TO_NAME_LOGISTICS.put(101L, "龙邦速递"); - ID_TO_NAME_LOGISTICS.put(102L, "乐捷递"); - ID_TO_NAME_LOGISTICS.put(103L, "立即送"); - ID_TO_NAME_LOGISTICS.put(104L, "蓝弧快递"); - ID_TO_NAME_LOGISTICS.put(105L, "乐天速递"); - ID_TO_NAME_LOGISTICS.put(106L, "民航快递"); - ID_TO_NAME_LOGISTICS.put(107L, "美国快递"); - ID_TO_NAME_LOGISTICS.put(108L, "门对门"); - ID_TO_NAME_LOGISTICS.put(109L, "明亮物流"); - ID_TO_NAME_LOGISTICS.put(110L, "民邦速递"); - ID_TO_NAME_LOGISTICS.put(111L, "闽盛快递"); - ID_TO_NAME_LOGISTICS.put(112L, "麦力快递"); - ID_TO_NAME_LOGISTICS.put(113L, "能达速递"); - ID_TO_NAME_LOGISTICS.put(114L, "偌亚奥国际"); - ID_TO_NAME_LOGISTICS.put(115L, "平安达腾飞"); - ID_TO_NAME_LOGISTICS.put(116L, "陪行物流"); - ID_TO_NAME_LOGISTICS.put(117L, "全日通快递"); - ID_TO_NAME_LOGISTICS.put(118L, "全晨快递"); - ID_TO_NAME_LOGISTICS.put(119L, "秦邦快运"); - ID_TO_NAME_LOGISTICS.put(120L, "如风达快递"); - ID_TO_NAME_LOGISTICS.put(121L, "日昱物流"); - ID_TO_NAME_LOGISTICS.put(122L, "瑞丰速递"); - ID_TO_NAME_LOGISTICS.put(123L, "山东海红"); - ID_TO_NAME_LOGISTICS.put(124L, "盛辉物流"); - ID_TO_NAME_LOGISTICS.put(125L, "世运快递"); - ID_TO_NAME_LOGISTICS.put(126L, "盛丰物流"); - ID_TO_NAME_LOGISTICS.put(127L, "上大物流"); - ID_TO_NAME_LOGISTICS.put(128L, "三态速递"); - ID_TO_NAME_LOGISTICS.put(129L, "申通E物流"); - ID_TO_NAME_LOGISTICS.put(130L, "圣安物流"); - ID_TO_NAME_LOGISTICS.put(131L, "山西红马甲"); - ID_TO_NAME_LOGISTICS.put(132L, "穗佳物流"); - ID_TO_NAME_LOGISTICS.put(133L, "沈阳佳惠尔"); - ID_TO_NAME_LOGISTICS.put(134L, "上海林道货运"); - ID_TO_NAME_LOGISTICS.put(135L, "十方通物流"); - ID_TO_NAME_LOGISTICS.put(136L, "山东广通速递"); - ID_TO_NAME_LOGISTICS.put(137L, "顺捷丰达"); - ID_TO_NAME_LOGISTICS.put(138L, "TTNT快递"); - ID_TO_NAME_LOGISTICS.put(139L, "天地华宇"); - ID_TO_NAME_LOGISTICS.put(140L, "通和天下"); - ID_TO_NAME_LOGISTICS.put(141L, "天纵物流"); - ID_TO_NAME_LOGISTICS.put(142L, "同舟行物流"); - ID_TO_NAME_LOGISTICS.put(143L, "腾达速递"); - ID_TO_NAME_LOGISTICS.put(144L, "UC优速快递"); - ID_TO_NAME_LOGISTICS.put(145L, "万象物流"); - ID_TO_NAME_LOGISTICS.put(146L, "微特派"); - ID_TO_NAME_LOGISTICS.put(147L, "万家物流"); - ID_TO_NAME_LOGISTICS.put(148L, "万博快递"); - ID_TO_NAME_LOGISTICS.put(149L, "希优特快递"); - ID_TO_NAME_LOGISTICS.put(150L, "新邦物流"); - ID_TO_NAME_LOGISTICS.put(151L, "信丰物流"); - ID_TO_NAME_LOGISTICS.put(152L, "祥龙运通物流"); - ID_TO_NAME_LOGISTICS.put(153L, "西安城联速递"); - ID_TO_NAME_LOGISTICS.put(154L, "西安喜来快递"); - ID_TO_NAME_LOGISTICS.put(155L, "鑫世锐达"); - ID_TO_NAME_LOGISTICS.put(156L, "鑫通宝物流"); - ID_TO_NAME_LOGISTICS.put(157L, "运通快递"); - ID_TO_NAME_LOGISTICS.put(158L, "远成物流"); - ID_TO_NAME_LOGISTICS.put(159L, "亚风速递"); - ID_TO_NAME_LOGISTICS.put(160L, "优速快递"); - ID_TO_NAME_LOGISTICS.put(161L, "亿顺航"); - ID_TO_NAME_LOGISTICS.put(162L, "越丰物流"); - ID_TO_NAME_LOGISTICS.put(163L, "源安达快递"); - ID_TO_NAME_LOGISTICS.put(164L, "原飞航物流"); - ID_TO_NAME_LOGISTICS.put(165L, "邮政EMS速递"); - ID_TO_NAME_LOGISTICS.put(166L, "银捷速递"); - ID_TO_NAME_LOGISTICS.put(167L, "一统飞鸿"); - ID_TO_NAME_LOGISTICS.put(168L, "宇鑫物流"); - ID_TO_NAME_LOGISTICS.put(169L, "易通达"); - ID_TO_NAME_LOGISTICS.put(170L, "邮必佳"); - ID_TO_NAME_LOGISTICS.put(171L, "一柒物流"); - ID_TO_NAME_LOGISTICS.put(172L, "音素快运"); - ID_TO_NAME_LOGISTICS.put(173L, "亿领速运"); - ID_TO_NAME_LOGISTICS.put(174L, "煜嘉物流"); - ID_TO_NAME_LOGISTICS.put(175L, "英脉物流"); - ID_TO_NAME_LOGISTICS.put(176L, "云南中诚"); - ID_TO_NAME_LOGISTICS.put(177L, "中铁快运"); - ID_TO_NAME_LOGISTICS.put(178L, "中铁物流"); - ID_TO_NAME_LOGISTICS.put(179L, "中邮物流"); - ID_TO_NAME_LOGISTICS.put(180L, "邮政快递"); - ID_TO_NAME_LOGISTICS.put(181L, "郑州建华"); - ID_TO_NAME_LOGISTICS.put(182L, "中速快件"); - ID_TO_NAME_LOGISTICS.put(183L, "中天万运"); - ID_TO_NAME_LOGISTICS.put(184L, "中睿速递"); - ID_TO_NAME_LOGISTICS.put(185L, "增益速递"); - ID_TO_NAME_LOGISTICS.put(186L, "郑州速捷"); - ID_TO_NAME_LOGISTICS.put(187L, "智通物流"); - -// // 把enum中的最初的标准15个快递公司和其它也加进来 -// LogisticsCompanyEnum[] firstArray = LogisticsCompanyEnum.values(); -// for (int i = 0; i < firstArray.length; i++) { -// ID_TO_NAME_LOGISTICS.put(new Long(firstArray[i].getLogisticsCompanyId()), -// firstArray[i].getLogisticsCompanyName()); -// } - } + static int a; + + static class Node { + int coin; + + int index; + + int sum = 0; + + Node parent; + + int depth = 1; + + List children = new ArrayList<>(); + + public Node(int coin, int index) { + this.coin = coin; + this.index = index; + } + + public static void buildSum(Node node, int depth) { + node.sum = node.coin; + node.depth = depth; + if (!node.children.isEmpty()) { + for (Node childNode : node.children) { + buildSum(childNode, depth + 1); + node.sum += childNode.sum; + } + } + } + + } + + static String stringGameWinner(String s, String p) { + // Complete this function + boolean amandaWin; + if (s.length() < p.length()) { + amandaWin = false; + } else { + int distance = s.length() - p.length(); + if ((distance & 1) == 0 && s.contains(p)) { + amandaWin = true; + } else { + amandaWin = false; + } + } + return amandaWin ? "Amanda" : "Steven"; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + // Return the number of non-empty perfect subsequences mod 1000000007 + int q = in.nextInt(); + PerfectString perfectString = new PerfectString(); + for (int a0 = 0; a0 < q; a0++) { + String s = in.next(); + long result = perfectString.perfectNum(s); + System.out.println(result); + } + } + + public class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + + public static ListNode rotateRight(ListNode head, int k) { + if (head == null || k <= 0) { + return head; + } + int length = 0; + ListNode node = head; + while (node != null) { + length += 1; + node = node.next; + } + if (length == 1) { + return head; + } + k = k % length; + ListNode forEnding = head; + for (int i = 0; i < length - k - 1; i++) { + forEnding = forEnding.next; + } + ListNode forHead = forEnding.next; + forEnding.next = null; + + ListNode actualEnd = forHead; + while (actualEnd.next != null) { + actualEnd = actualEnd.next; + } + + forEnding.next = null; + actualEnd.next = head; + return forHead; + } + + private static int addNode(int sum, Node first, Node second) { + boolean sub = false; + Node ancestor = null; + Node successor = null; + if (first.depth != second.depth) { + if (first.depth < second.depth) { + while (second.parent != null) { + second = second.parent; + if (first == second) { + sub = true; + ancestor = first; + successor = second; + break; + } + } + } else { + while (first.parent != null) { + first = first.parent; + if (first == second) { + sub = true; + ancestor = second; + successor = first; + break; + } + } + } + } + if (sub) { + return fixValue(sum - ancestor.sum, successor.sum, ancestor.sum - successor.sum); + } else { + return fixValue(first.sum, second.sum, sum - first.sum - second.sum); + } + } + + private static int fixValue(int first, int second, int left) { + if (first == second && first > left) { + return first - left; + } + if (second == left && second > first) { + return second - first; + } + if (first == left && first > second) { + return first - second; + } + return -1; + } + + private static void addRecursive(List powerList, int index, int sum, int[] result) { + if (sum >= result.length) { + return; + } + if (index >= powerList.size()) { + result[sum] += 1; + return; + } + addRecursive(powerList, index + 1, sum + powerList.get(index), result); + addRecursive(powerList, index + 1, sum, result); + } + + public class A { + + } + + public static class B { + } + + public enum LogisticsCompanyEnum { + + QITA("Q", 0, "其它"), SHUNFENG("S", 1, "顺丰速运"), ZHONGTONG("Z", 2, "中通快递"), SHENTONG("S", 3, "申通快递"), YUANTONG("Y", + 4, "圆通快递"), YUNDA("Y", 5, "韵达快递"), + EMS("E", 6, "EMS"), TIANTIAN("T", 7, "天天快递"), GUOTONG("G", 8, "国通快递"), SUER("S", 9, "速尔快递"), BAISHI("B", 10, + "百世汇通"), LIANBANG("L", 11, "联邦快递"), + QUANFENG("Q", 12, "全峰快递"), ZAIJISONG("Z", 13, "宅急送"), QUANYI("Q", 14, "全一快递"), UPS("U", 15, "UPS快递"), + ZHONG_WAI_YUN("Z", 16, "中外运速递"),; + + private String initial; + + private int logisticsCompanyId; + + private String logisticsCompanyName; + + private LogisticsCompanyEnum(String initial, int logisticsCompanyId, String logisticsCompanyName) { + this.initial = initial; + this.logisticsCompanyId = logisticsCompanyId; + this.logisticsCompanyName = logisticsCompanyName; + } + + public String getInitial() { + return initial; + } + + public int getLogisticsCompanyId() { + return logisticsCompanyId; + } + + public String getLogisticsCompanyName() { + return logisticsCompanyName; + } + + } + + private static final Map ID_TO_NAME_LOGISTICS = new HashMap(); + + static { + ID_TO_NAME_LOGISTICS.put(16L, "中外运速递"); + ID_TO_NAME_LOGISTICS.put(17L, "E特快"); + ID_TO_NAME_LOGISTICS.put(18L, "芝麻开门"); + ID_TO_NAME_LOGISTICS.put(19L, "赛澳递"); + ID_TO_NAME_LOGISTICS.put(20L, "安能物流"); + ID_TO_NAME_LOGISTICS.put(21L, "安迅物流"); + ID_TO_NAME_LOGISTICS.put(22L, "巴伦支快递"); + ID_TO_NAME_LOGISTICS.put(23L, "北青小红帽"); + ID_TO_NAME_LOGISTICS.put(24L, "百福东方物流"); + ID_TO_NAME_LOGISTICS.put(25L, "邦送物流"); + ID_TO_NAME_LOGISTICS.put(26L, "宝凯物流"); + ID_TO_NAME_LOGISTICS.put(27L, "百千诚物流"); + ID_TO_NAME_LOGISTICS.put(28L, "博源恒通"); + ID_TO_NAME_LOGISTICS.put(29L, "百成大达物流"); + ID_TO_NAME_LOGISTICS.put(30L, "百世快运"); + ID_TO_NAME_LOGISTICS.put(31L, "COE(东方快递)"); + ID_TO_NAME_LOGISTICS.put(32L, "城市100"); + ID_TO_NAME_LOGISTICS.put(33L, "传喜物流"); + ID_TO_NAME_LOGISTICS.put(34L, "城际速递"); + ID_TO_NAME_LOGISTICS.put(35L, "成都立即送"); + ID_TO_NAME_LOGISTICS.put(36L, "出口易"); + ID_TO_NAME_LOGISTICS.put(37L, "晟邦物流"); + ID_TO_NAME_LOGISTICS.put(38L, "DHL快递"); + ID_TO_NAME_LOGISTICS.put(39L, "DHL"); + ID_TO_NAME_LOGISTICS.put(40L, "德邦大田物流"); + ID_TO_NAME_LOGISTICS.put(41L, "东方快递"); + ID_TO_NAME_LOGISTICS.put(42L, "递四方"); + ID_TO_NAME_LOGISTICS.put(43L, "大洋物流"); + ID_TO_NAME_LOGISTICS.put(44L, "店通快递"); + ID_TO_NAME_LOGISTICS.put(45L, "德创物流"); + ID_TO_NAME_LOGISTICS.put(46L, "东红物流"); + ID_TO_NAME_LOGISTICS.put(47L, "D速物流"); + ID_TO_NAME_LOGISTICS.put(48L, "东瀚物流"); + ID_TO_NAME_LOGISTICS.put(49L, "达方物流"); + ID_TO_NAME_LOGISTICS.put(50L, "俄顺达"); + ID_TO_NAME_LOGISTICS.put(51L, "FedEx快递"); + ID_TO_NAME_LOGISTICS.put(52L, "飞康达物流"); + ID_TO_NAME_LOGISTICS.put(53L, "飞豹快递"); + ID_TO_NAME_LOGISTICS.put(54L, "飞狐快递"); + ID_TO_NAME_LOGISTICS.put(55L, "凡宇速递"); + ID_TO_NAME_LOGISTICS.put(56L, "颿达国际"); + ID_TO_NAME_LOGISTICS.put(57L, "飞远配送"); + ID_TO_NAME_LOGISTICS.put(58L, "飞鹰物流"); + ID_TO_NAME_LOGISTICS.put(59L, "风行天下"); + ID_TO_NAME_LOGISTICS.put(60L, "GATI快递"); + ID_TO_NAME_LOGISTICS.put(61L, "港中能达物流"); + ID_TO_NAME_LOGISTICS.put(62L, "共速达"); + ID_TO_NAME_LOGISTICS.put(63L, "广通速递"); + ID_TO_NAME_LOGISTICS.put(64L, "广东速腾物流"); + ID_TO_NAME_LOGISTICS.put(65L, "港快速递"); + ID_TO_NAME_LOGISTICS.put(66L, "高铁速递"); + ID_TO_NAME_LOGISTICS.put(67L, "冠达快递"); + ID_TO_NAME_LOGISTICS.put(68L, "华宇物流"); + ID_TO_NAME_LOGISTICS.put(69L, "恒路物流"); + ID_TO_NAME_LOGISTICS.put(70L, "好来运快递"); + ID_TO_NAME_LOGISTICS.put(71L, "华夏龙物流"); + ID_TO_NAME_LOGISTICS.put(72L, "海航天天"); + ID_TO_NAME_LOGISTICS.put(73L, "河北建华"); + ID_TO_NAME_LOGISTICS.put(74L, "海盟速递"); + ID_TO_NAME_LOGISTICS.put(75L, "华企快运"); + ID_TO_NAME_LOGISTICS.put(76L, "昊盛物流"); + ID_TO_NAME_LOGISTICS.put(77L, "户通物流"); + ID_TO_NAME_LOGISTICS.put(78L, "华航快递"); + ID_TO_NAME_LOGISTICS.put(79L, "黄马甲快递"); + ID_TO_NAME_LOGISTICS.put(80L, "合众速递(UCS)"); + ID_TO_NAME_LOGISTICS.put(81L, "韩润物流"); + ID_TO_NAME_LOGISTICS.put(82L, "皇家物流"); + ID_TO_NAME_LOGISTICS.put(83L, "伙伴物流"); + ID_TO_NAME_LOGISTICS.put(84L, "红马速递"); + ID_TO_NAME_LOGISTICS.put(85L, "汇文配送"); + ID_TO_NAME_LOGISTICS.put(86L, "华赫物流"); + ID_TO_NAME_LOGISTICS.put(87L, "佳吉物流"); + ID_TO_NAME_LOGISTICS.put(88L, "佳怡物流"); + ID_TO_NAME_LOGISTICS.put(89L, "加运美快递"); + ID_TO_NAME_LOGISTICS.put(90L, "急先达物流"); + ID_TO_NAME_LOGISTICS.put(91L, "京广速递"); + ID_TO_NAME_LOGISTICS.put(92L, "晋越快递"); + ID_TO_NAME_LOGISTICS.put(93L, "捷特快递"); + ID_TO_NAME_LOGISTICS.put(94L, "久易快递"); + ID_TO_NAME_LOGISTICS.put(95L, "快捷快递"); + ID_TO_NAME_LOGISTICS.put(96L, "康力物流"); + ID_TO_NAME_LOGISTICS.put(97L, "跨越速运"); + ID_TO_NAME_LOGISTICS.put(98L, "快优达速递"); + ID_TO_NAME_LOGISTICS.put(99L, "快淘快递"); + ID_TO_NAME_LOGISTICS.put(100L, "联昊通物流"); + ID_TO_NAME_LOGISTICS.put(101L, "龙邦速递"); + ID_TO_NAME_LOGISTICS.put(102L, "乐捷递"); + ID_TO_NAME_LOGISTICS.put(103L, "立即送"); + ID_TO_NAME_LOGISTICS.put(104L, "蓝弧快递"); + ID_TO_NAME_LOGISTICS.put(105L, "乐天速递"); + ID_TO_NAME_LOGISTICS.put(106L, "民航快递"); + ID_TO_NAME_LOGISTICS.put(107L, "美国快递"); + ID_TO_NAME_LOGISTICS.put(108L, "门对门"); + ID_TO_NAME_LOGISTICS.put(109L, "明亮物流"); + ID_TO_NAME_LOGISTICS.put(110L, "民邦速递"); + ID_TO_NAME_LOGISTICS.put(111L, "闽盛快递"); + ID_TO_NAME_LOGISTICS.put(112L, "麦力快递"); + ID_TO_NAME_LOGISTICS.put(113L, "能达速递"); + ID_TO_NAME_LOGISTICS.put(114L, "偌亚奥国际"); + ID_TO_NAME_LOGISTICS.put(115L, "平安达腾飞"); + ID_TO_NAME_LOGISTICS.put(116L, "陪行物流"); + ID_TO_NAME_LOGISTICS.put(117L, "全日通快递"); + ID_TO_NAME_LOGISTICS.put(118L, "全晨快递"); + ID_TO_NAME_LOGISTICS.put(119L, "秦邦快运"); + ID_TO_NAME_LOGISTICS.put(120L, "如风达快递"); + ID_TO_NAME_LOGISTICS.put(121L, "日昱物流"); + ID_TO_NAME_LOGISTICS.put(122L, "瑞丰速递"); + ID_TO_NAME_LOGISTICS.put(123L, "山东海红"); + ID_TO_NAME_LOGISTICS.put(124L, "盛辉物流"); + ID_TO_NAME_LOGISTICS.put(125L, "世运快递"); + ID_TO_NAME_LOGISTICS.put(126L, "盛丰物流"); + ID_TO_NAME_LOGISTICS.put(127L, "上大物流"); + ID_TO_NAME_LOGISTICS.put(128L, "三态速递"); + ID_TO_NAME_LOGISTICS.put(129L, "申通E物流"); + ID_TO_NAME_LOGISTICS.put(130L, "圣安物流"); + ID_TO_NAME_LOGISTICS.put(131L, "山西红马甲"); + ID_TO_NAME_LOGISTICS.put(132L, "穗佳物流"); + ID_TO_NAME_LOGISTICS.put(133L, "沈阳佳惠尔"); + ID_TO_NAME_LOGISTICS.put(134L, "上海林道货运"); + ID_TO_NAME_LOGISTICS.put(135L, "十方通物流"); + ID_TO_NAME_LOGISTICS.put(136L, "山东广通速递"); + ID_TO_NAME_LOGISTICS.put(137L, "顺捷丰达"); + ID_TO_NAME_LOGISTICS.put(138L, "TTNT快递"); + ID_TO_NAME_LOGISTICS.put(139L, "天地华宇"); + ID_TO_NAME_LOGISTICS.put(140L, "通和天下"); + ID_TO_NAME_LOGISTICS.put(141L, "天纵物流"); + ID_TO_NAME_LOGISTICS.put(142L, "同舟行物流"); + ID_TO_NAME_LOGISTICS.put(143L, "腾达速递"); + ID_TO_NAME_LOGISTICS.put(144L, "UC优速快递"); + ID_TO_NAME_LOGISTICS.put(145L, "万象物流"); + ID_TO_NAME_LOGISTICS.put(146L, "微特派"); + ID_TO_NAME_LOGISTICS.put(147L, "万家物流"); + ID_TO_NAME_LOGISTICS.put(148L, "万博快递"); + ID_TO_NAME_LOGISTICS.put(149L, "希优特快递"); + ID_TO_NAME_LOGISTICS.put(150L, "新邦物流"); + ID_TO_NAME_LOGISTICS.put(151L, "信丰物流"); + ID_TO_NAME_LOGISTICS.put(152L, "祥龙运通物流"); + ID_TO_NAME_LOGISTICS.put(153L, "西安城联速递"); + ID_TO_NAME_LOGISTICS.put(154L, "西安喜来快递"); + ID_TO_NAME_LOGISTICS.put(155L, "鑫世锐达"); + ID_TO_NAME_LOGISTICS.put(156L, "鑫通宝物流"); + ID_TO_NAME_LOGISTICS.put(157L, "运通快递"); + ID_TO_NAME_LOGISTICS.put(158L, "远成物流"); + ID_TO_NAME_LOGISTICS.put(159L, "亚风速递"); + ID_TO_NAME_LOGISTICS.put(160L, "优速快递"); + ID_TO_NAME_LOGISTICS.put(161L, "亿顺航"); + ID_TO_NAME_LOGISTICS.put(162L, "越丰物流"); + ID_TO_NAME_LOGISTICS.put(163L, "源安达快递"); + ID_TO_NAME_LOGISTICS.put(164L, "原飞航物流"); + ID_TO_NAME_LOGISTICS.put(165L, "邮政EMS速递"); + ID_TO_NAME_LOGISTICS.put(166L, "银捷速递"); + ID_TO_NAME_LOGISTICS.put(167L, "一统飞鸿"); + ID_TO_NAME_LOGISTICS.put(168L, "宇鑫物流"); + ID_TO_NAME_LOGISTICS.put(169L, "易通达"); + ID_TO_NAME_LOGISTICS.put(170L, "邮必佳"); + ID_TO_NAME_LOGISTICS.put(171L, "一柒物流"); + ID_TO_NAME_LOGISTICS.put(172L, "音素快运"); + ID_TO_NAME_LOGISTICS.put(173L, "亿领速运"); + ID_TO_NAME_LOGISTICS.put(174L, "煜嘉物流"); + ID_TO_NAME_LOGISTICS.put(175L, "英脉物流"); + ID_TO_NAME_LOGISTICS.put(176L, "云南中诚"); + ID_TO_NAME_LOGISTICS.put(177L, "中铁快运"); + ID_TO_NAME_LOGISTICS.put(178L, "中铁物流"); + ID_TO_NAME_LOGISTICS.put(179L, "中邮物流"); + ID_TO_NAME_LOGISTICS.put(180L, "邮政快递"); + ID_TO_NAME_LOGISTICS.put(181L, "郑州建华"); + ID_TO_NAME_LOGISTICS.put(182L, "中速快件"); + ID_TO_NAME_LOGISTICS.put(183L, "中天万运"); + ID_TO_NAME_LOGISTICS.put(184L, "中睿速递"); + ID_TO_NAME_LOGISTICS.put(185L, "增益速递"); + ID_TO_NAME_LOGISTICS.put(186L, "郑州速捷"); + ID_TO_NAME_LOGISTICS.put(187L, "智通物流"); + + // // 把enum中的最初的标准15个快递公司和其它也加进来 + // LogisticsCompanyEnum[] firstArray = LogisticsCompanyEnum.values(); + // for (int i = 0; i < firstArray.length; i++) { + // ID_TO_NAME_LOGISTICS.put(new Long(firstArray[i].getLogisticsCompanyId()), + // firstArray[i].getLogisticsCompanyName()); + // } + } } diff --git a/src/main/java/org/wcong/test/algorithm/cracking/dp_divide_conque/BooleanEvaluation.java b/src/main/java/org/wcong/test/algorithm/cracking/dp_divide_conque/BooleanEvaluation.java new file mode 100644 index 0000000..57e988e --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/cracking/dp_divide_conque/BooleanEvaluation.java @@ -0,0 +1,21 @@ +package org.wcong.test.algorithm.cracking.dp_divide_conque; + +import java.util.List; + +/** + * given a boolean evaluation consisting of symbol + * 0(false),1(true),&(and),|(OR),and ^(XOR) and a desired boolean result Result + * implement a function to count the number of ways of parenthesizing the expressions + * such that it evaluates to result. + * the expression should be fully parenthesized + * + * @author wcong + * @since 19/04/2017 + */ +public class BooleanEvaluation { + + public int count(String expression, boolean result) { + return 0; + } + +} diff --git a/src/main/java/org/wcong/test/algorithm/dp/LongestCommonSubsequence.java b/src/main/java/org/wcong/test/algorithm/dp/LongestCommonSubSequence.java similarity index 100% rename from src/main/java/org/wcong/test/algorithm/dp/LongestCommonSubsequence.java rename to src/main/java/org/wcong/test/algorithm/dp/LongestCommonSubSequence.java diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/array/Candy.java b/src/main/java/org/wcong/test/algorithm/leetcode/array/Candy.java new file mode 100644 index 0000000..ee49783 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/array/Candy.java @@ -0,0 +1,47 @@ +package org.wcong.test.algorithm.leetcode.array; + +/** + * There are N children standing in a line. Each child is assigned a rating value. + * You are giving candies to these children subjected to the following requirements: + * 1. Each child must have at least one candy. + * 2. Children with a higher rating get more candies than their neighbors. + * What is the minimum candies you must give? + * + * @author wcong + * @since 19/06/2017 + */ +public class Candy { + public int candy(int[] ratings) { + int candies = 1; + int[] candy = new int[ratings.length]; + candy[0] = 1; + for (int i = 1; i < ratings.length; i++) { + if (ratings[i] > ratings[i - 1]) { + candy[i] = candy[i - 1] + 1; + candies += candy[i]; + } else if (ratings[i] < ratings[i - 1]) { + int lastIndex = i; + int lastRating = ratings[i]; + while (lastIndex + 1 < ratings.length && lastRating > ratings[lastIndex + 1]) { + lastIndex += 1; + lastRating = ratings[lastIndex]; + } + int num = 1; + for (int j = lastIndex; j >= i; j--) { + candy[j] = num; + candies += num; + num += 1; + } + if (candy[i - 1] < num) { + candies += num - candy[i - 1]; + candy[i - 1] = num; + } + i = lastIndex; + } else { + candy[i] = 1; + candies += 1; + } + } + return candies; + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/array/CreateMaximumNumber.java b/src/main/java/org/wcong/test/algorithm/leetcode/array/CreateMaximumNumber.java new file mode 100644 index 0000000..69d1768 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/array/CreateMaximumNumber.java @@ -0,0 +1,126 @@ +package org.wcong.test.algorithm.leetcode.array; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Given two arrays of length m and n with digits 0-9 representing two numbers. + * Create the maximum number of length k <= m + n from digits of the two. + * The relative order of the digits from the same array must be preserved. + * Return an array of the k digits. + * You should try to optimize your time and space complexity + * + * @author wcong + * @since 13/06/2017 + */ +public class CreateMaximumNumber { + + private int[] maxNumber; + + public int[] maxNumberBruteForce(int[] nums1, int[] nums2, int k) { + int total = nums1.length + nums2.length; + k = total > k ? k : total; + maxNumber = new int[k]; + iterateMaxNumber(nums1, 0, nums2, 0, new int[k], k); + return maxNumber; + } + + private void iterateMaxNumber(int[] nums1, int index1, int[] nums2, int index2, int[] number, int left) { + if (index1 >= nums1.length && index2 >= nums2.length && left > 0) { + return; + } + if (left <= 0) { + if (arrayCompare(number, maxNumber)) { + maxNumber = Arrays.copyOf(number, number.length); + } + return; + } + if (index1 < nums1.length) { + number[number.length - left] = nums1[index1]; + iterateMaxNumber(nums1, index1 + 1, nums2, index2, number, left - 1); + iterateMaxNumber(nums1, index1 + 1, nums2, index2, number, left); + } + if (index2 < nums2.length) { + number[number.length - left] = nums2[index2]; + iterateMaxNumber(nums1, index1, nums2, index2 + 1, number, left - 1); + iterateMaxNumber(nums1, index1, nums2, index2 + 1, number, left); + } + } + + private boolean arrayCompare(int[] array1, int[] array2) { + for (int i = 0; i < array2.length; i++) { + if (array1[i] > array2[i]) { + return true; + } else if (array1[i] < array2[i]) { + return false; + } + } + return false; + } + + static class Index { + public Index(boolean first, int index) { + this.first = first; + this.index = index; + } + + boolean first = false; + int index = 0; + } + + public int[] maxNumberGreed(int[] nums1, int[] nums2, int k) { + int total = nums1.length + nums2.length; + k = total > k ? k : total; + maxNumber = new int[k]; + maxNumberGreed(nums1, 0, nums2, 0, k, new int[k]); + return maxNumber; + } + + private void maxNumberGreed(int[] nums1, int index1, int[] nums2, int index2, int left, int[] current) { + if (left <= 0) { + if (arrayCompare(current, maxNumber)) { + maxNumber = Arrays.copyOf(current, current.length); + } + return; + } + List maxIndexList = findMaxIndex(nums1, index1, nums2, index2, left); + for (Index index : maxIndexList) { + if (index.first) { + current[current.length - left] = nums1[index.index]; + maxNumberGreed(nums1, index.index + 1, nums2, index2, left - 1, current); + } else { + current[current.length - left] = nums2[index.index]; + maxNumberGreed(nums1, index1, nums2, index.index + 1, left - 1, current); + } + } + } + + private List findMaxIndex(int[] nums1, int index1, int[] nums2, int index2, int left) { + List maxList = new ArrayList<>(); + int firstEnd = nums1.length - left + nums2.length - index2; + firstEnd = firstEnd >= nums1.length ? nums1.length - 1 : firstEnd; + int max = 0; + for (int i = index1; i <= firstEnd; i++) { + if (nums1[i] > max) { + maxList.clear(); + maxList.add(new Index(true, i)); + max = nums1[i]; + } else if (nums1[i] == max) { + maxList.add(new Index(true, i)); + } + } + int secondEnd = nums2.length - left + nums1.length - index1; + secondEnd = secondEnd >= nums2.length ? nums2.length - 1 : secondEnd; + for (int i = index2; i <= secondEnd; i++) { + if (nums2[i] > max) { + maxList.clear(); + maxList.add(new Index(false, i)); + max = nums2[i]; + } else if (nums2[i] == max) { + maxList.add(new Index(false, i)); + } + } + return maxList; + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/array/MaxPointsOnALine.java b/src/main/java/org/wcong/test/algorithm/leetcode/array/MaxPointsOnALine.java new file mode 100644 index 0000000..2db32fd --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/array/MaxPointsOnALine.java @@ -0,0 +1,162 @@ +package org.wcong.test.algorithm.leetcode.array; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Given n points on a 2D plane + * find the maximum number of points that lie on the same straight line. + * + * @author wcong + * @since 10/05/2017 + */ +public class MaxPointsOnALine { + + public int maxPointsBruteForce(Point[] points) { + if (points == null) { + return 0; + } + if (points.length < 2) { + return points.length; + } + int maxPoints = 0; + for (int firstIndex = 0; firstIndex < points.length; firstIndex++) { + for (int secondIndex = firstIndex + 1; secondIndex < points.length; secondIndex++) { + Point firstPoint = points[firstIndex]; + Point secondPoint = points[secondIndex]; + double angel = 0; + if (firstPoint.y != secondPoint.y) { + angel = firstPoint.x > secondPoint.x ? + (firstPoint.x - secondPoint.x) / (firstPoint.y - secondPoint.y) : + (secondPoint.x - firstPoint.x) / (secondPoint.y - firstPoint.y); + } + int pointsNum = 2; + for (int leftIndex = secondIndex + 1; leftIndex < points.length; leftIndex++) { + Point nextPoint = points[leftIndex]; + if (firstPoint.y == nextPoint.y) { + if (firstPoint.y == secondPoint.y) { + pointsNum += 1; + } + continue; + } + double nextAngel = firstPoint.x > nextPoint.x ? + (firstPoint.x - nextPoint.x) / (firstPoint.y - nextPoint.y) : + (nextPoint.x - firstPoint.x) / (nextPoint.y - firstPoint.y); + if (angel == nextAngel) { + pointsNum += 1; + } + } + if (pointsNum > maxPoints) { + maxPoints = pointsNum; + } + } + } + return maxPoints; + } + + static class MyPoint { + Point point; + + String key; + + int count; + } + + public int maxPointsDp(Point[] points) { + if (points == null) { + return 0; + } + if (points.length < 2) { + return points.length; + } + Map pointCount = new HashMap<>(); + for (Point point : points) { + String key = point.x + "_" + point.y; + if (pointCount.containsKey(key)) { + pointCount.get(key).count += 1; + } else { + MyPoint myPoint = new MyPoint(); + myPoint.point = point; + myPoint.key = key; + myPoint.count = 1; + pointCount.put(key, myPoint); + } + } + List myPointList = new ArrayList<>(pointCount.values()); + if( myPointList.size()==1 ){ + return myPointList.get(0).count; + } + Set usedPoints = new HashSet<>(); + int maxPoints = 0; + for (int firstIndex = 0; firstIndex < myPointList.size(); firstIndex++) { + for (int secondIndex = firstIndex + 1; secondIndex < myPointList.size(); secondIndex++) { + MyPoint firstPoint = myPointList.get(firstIndex); + MyPoint secondPoint = myPointList.get(secondIndex); + if (usedPoints.contains(firstIndex + "_" + secondIndex)) { + continue; + } + double angel = 0; + if (firstPoint.point.y != secondPoint.point.y) { + angel = firstPoint.point.x > secondPoint.point.x ? + (firstPoint.point.x - secondPoint.point.x) / (double)(firstPoint.point.y - secondPoint.point.y) : + (secondPoint.point.x - firstPoint.point.x) / (double)(secondPoint.point.y - firstPoint.point.y); + } + int pointsNum = firstPoint.count + secondPoint.count; + List sameIndex = new LinkedList<>(); + for (int leftIndex = secondIndex + 1; leftIndex < myPointList.size(); leftIndex++) { + if (usedPoints.contains(secondIndex + "_" + leftIndex)) { + continue; + } + MyPoint nextPoint = myPointList.get(leftIndex); + if (firstPoint.point.y == nextPoint.point.y) { + if (firstPoint.point.y == secondPoint.point.y) { + for (Integer lastIndex : sameIndex) { + usedPoints.add(lastIndex + "_" + leftIndex); + } + sameIndex.add(leftIndex); + pointsNum += nextPoint.count; + } + continue; + } + double nextAngel = firstPoint.point.x > nextPoint.point.x ? + (firstPoint.point.x - nextPoint.point.x) / (double)(firstPoint.point.y - nextPoint.point.y) : + (nextPoint.point.x - firstPoint.point.x) / (double)(nextPoint.point.y - firstPoint.point.y); + if (angel == nextAngel) { + for (Integer lastIndex : sameIndex) { + usedPoints.add(lastIndex + "_" + leftIndex); + } + sameIndex.add(leftIndex); + pointsNum += nextPoint.count; + } + } + + if (pointsNum > maxPoints) { + maxPoints = pointsNum; + } + } + } + return maxPoints; + } + + public static class Point { + int x; + + int y; + + Point() { + x = 0; + y = 0; + } + + public Point(int a, int b) { + x = a; + y = b; + } + } + +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/array/MedianOfTwoSortedArray.java b/src/main/java/org/wcong/test/algorithm/leetcode/array/MedianOfTwoSortedArray.java new file mode 100644 index 0000000..bdb6a74 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/array/MedianOfTwoSortedArray.java @@ -0,0 +1,52 @@ +package org.wcong.test.algorithm.leetcode.array; + +/** + * There are two sorted arrays nums1 and nums2 of size m and n respectively. + * Find the median of the two sorted arrays. + * The overall run time complexity should be O(log (m+n)). + * ......*....... + * .....*...... + * + * @author wcong + * @since 11/05/2017 + */ +public class MedianOfTwoSortedArray { + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + boolean isOdd = ((nums1.length + nums2.length) & 1) == 1; + int middle = (nums1.length + nums2.length) >> 1; + int nums1Start = 0; + int nums1End = nums1.length - 1; + int nums2Start = 0; + int nums2End = nums2.length - 1; + while (true) { + int nums1Middle = nums1Start + (nums1End - nums1Start) / 2; + int nums2Middle = nums2Start + (nums2End - nums2Start) / 2; + int currentPosition = nums1Middle + nums2Middle; + if (nums1[nums1Middle] == nums2[nums2Middle]) { + if (currentPosition == middle) { + break; + } else if (currentPosition < middle) { + nums1Start = nums1Middle; + nums2Start = nums2Middle; + } else { + nums1End = nums1Middle; + nums2End = nums2Middle; + } + } else if (nums1[nums1Middle] < nums2[nums2Middle]) { + nums2End = nums2Middle; + nums1Start = nums1Middle; + } else { + nums1End = nums1Middle; + nums2Start = nums2Middle; + } + if (nums1End == nums1Start && nums2End == nums2Start) { + break; + } + } + if (isOdd) { + return nums1[nums1End] > nums2[nums2End] ? nums1[nums1End] : nums2[nums2End]; + } else { + return ((double) (nums1[nums1End] + nums2[nums2End])) / 2; + } + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/array/NumbersOfIslands.java b/src/main/java/org/wcong/test/algorithm/leetcode/array/NumbersOfIslands.java new file mode 100644 index 0000000..7263b6f --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/array/NumbersOfIslands.java @@ -0,0 +1,44 @@ +package org.wcong.test.algorithm.leetcode.array; + +/** + * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. + * An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. + * You may assume all four edges of the grid are all surrounded by water. + * + * @author wcong + * @since 09/05/2017 + */ +public class NumbersOfIslands { + public int numIslandsBruteForce(char[][] grid) { + int nums = 0; + for (int row = 0; row < grid.length; row++) { + for (int column = 0; column < grid[row].length; column++) { + if (grid[row][column] == '1') { + nums += 1; + elimateLand(grid, row, column); + } + } + } + return nums; + } + + private void elimateLand(char[][] grid, int row, int column) { + if (grid[row][column] == '0') { + return; + } + grid[row][column] = '0'; + if (row > 0) { + elimateLand(grid, row - 1, column); + } + if (column > 0) { + elimateLand(grid, row, column - 1); + } + if (row < grid.length - 1) { + elimateLand(grid, row + 1, column); + } + if (column < grid[row].length - 1) { + elimateLand(grid, row, column + 1); + } + } + +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/array/ReversePairs.java b/src/main/java/org/wcong/test/algorithm/leetcode/array/ReversePairs.java new file mode 100644 index 0000000..364fe77 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/array/ReversePairs.java @@ -0,0 +1,85 @@ +package org.wcong.test.algorithm.leetcode.array; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Given an array nums + * we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j]. + * You need to return the number of important reverse pairs in the given array. + * + * @author wcong + * @since 04/05/2017 + */ +public class ReversePairs { + + public int reversePairsBruteForce(int[] nums) { + int pairs = 0; + for (int index = 0; index < nums.length; index++) { + for (int nextIndex = index + 1; nextIndex < nums.length; nextIndex++) { + if (nums[index] > 2 * nums[nextIndex]) { + pairs += 1; + } + } + } + return pairs; + } + + public int reversePairsDivideAndConquer(int[] nums) { + return reversePairsDivideAndConquer(nums, 0, nums.length - 1); + } + + private int reversePairsDivideAndConquer(int[] nums, int start, int end) { + if (start >= end) { + return 0; + } + int pairs = 0; + int middle = start + (end - start) / 2; + pairs += reversePairsDivideAndConquer(nums, start, middle); + pairs += reversePairsDivideAndConquer(nums, middle + 1, end); + int leftIndex = start; + for (int rightIndex = middle + 1; rightIndex <= end; rightIndex++) { + long currentNum = nums[rightIndex]; + for (; leftIndex <= middle; leftIndex++) { + if (2 * currentNum < nums[leftIndex]) { + pairs += middle - leftIndex + 1; + break; + } + } + } + + Arrays.sort(nums, start, end + 1); + return pairs; + } + + public int reversePairsLiner(int[] nums) { + List sorted = new LinkedList<>(); + int pairs = 0; + for (int soloNum : nums) { + pairs += countAndInsert(sorted, soloNum); + } + return pairs; + } + + private int countAndInsert(List sorted, Integer num) { + if (sorted.isEmpty()) { + sorted.add(num); + return 0; + } + int pairsIndex = 0; + int insertIndex = 0; + for (int integer : sorted) { + if (integer < num) { + insertIndex += 1; + } + if (integer > 2 * (long) num) { + break; + } + pairsIndex += 1; + } + sorted.add(insertIndex, num); + return sorted.size() - 1 - pairsIndex; + } + +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/numbers/NumberToWords.java b/src/main/java/org/wcong/test/algorithm/leetcode/numbers/NumberToWords.java new file mode 100644 index 0000000..3888218 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/numbers/NumberToWords.java @@ -0,0 +1,68 @@ +package org.wcong.test.algorithm.leetcode.numbers; + +/** + * Convert a non-negative integer to its english words representation. + * Given input is guaranteed to be less than 231 - 1. + * 123 -> "One Hundred Twenty Three" + * 12345 -> "Twelve Thousand Three Hundred Forty Five" + * 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" + * + * @author wcong + * @since 16/05/2017 + */ +public class NumberToWords { + + private static String[] LEVEL = new String[] { "", "Thousand", "Million", "Billion" }; + + private static String[] NUMBERS = new String[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", + "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", + "Eighteen", "Nineteen" }; + + private static String[] TEN_LEVEL = new String[] { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", + "Eighty", "Ninety" }; + + public String numberToWords(int num) { + if (num == 0) { + return "Zero"; + } + String words = ""; + int level = 0; + while (num > 0) { + String result = numberToWords(num % 1000, level); + if (words.length() > 0 && result.length() > 0) { + words = result + " " + words; + } else { + words = result + words; + } + num = num / 1000; + level += 1; + } + return words; + } + + private String numberToWords(int num, int level) { + StringBuilder stringBuilder = new StringBuilder(); + if (num >= 100) { + stringBuilder.append(NUMBERS[num / 100]).append(" ").append("Hundred"); + num = num % 100; + } + if (num >= 20) { + if (stringBuilder.length() > 0) { + stringBuilder.append(" "); + } + stringBuilder.append(TEN_LEVEL[num / 10]); + num = num % 10; + } + if (num > 0) { + if (stringBuilder.length() > 0) { + stringBuilder.append(" "); + } + stringBuilder.append(NUMBERS[num]); + } + if (level > 0 && stringBuilder.length() > 0) { + stringBuilder.append(" ").append(LEVEL[level]); + } + return stringBuilder.toString(); + } + +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/BestTimeBuySellStockIV.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/BestTimeBuySellStockIV.java new file mode 100644 index 0000000..c5b0250 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/BestTimeBuySellStockIV.java @@ -0,0 +1,78 @@ +package org.wcong.test.algorithm.leetcode.string; + +/** + * Say you have an array for which the ith element is the price of a given stock on day i. + * Design an algorithm to find the maximum profit. + * You may complete at most k transactions. + * Note: + * You may not engage in multiple transactions at the same time + * (ie, you must sell the stock before you buy again). + * + * @author wcong + * @since 08/06/2017 + */ +public class BestTimeBuySellStockIV { + + private Integer maxProfit; + + public int maxProfitBruteForce(int k, int[] prices) { + maxProfit = 0; + iterateOptions(k, 0, prices, false, 0, 0); + return maxProfit; + } + + private void iterateOptions(int transactions, int index, int[] prices, boolean isBuy, int currentPrice, int currentProfit) { + if (index >= prices.length || transactions <= 0) { + if (currentProfit > maxProfit) { + maxProfit = currentProfit; + } + return; + } + if (!isBuy) { + iterateOptions(transactions, index + 1, prices, true, prices[index], currentProfit); + iterateOptions(transactions, index + 1, prices, false, currentPrice, currentProfit); + } else { + iterateOptions(transactions - 1, index + 1, prices, false, prices[index], currentProfit + prices[index] - currentPrice); + iterateOptions(transactions, index + 1, prices, true, currentPrice, currentProfit); + } + } + + + static class Result { + int profit = 0; + int transactions = 0; + } + + public int maxProfitDp(int k, int[] prices) { + if (k <= 0 || prices.length == 0) { + return 0; + } + Result[] profits = new Result[prices.length]; + profits[0] = new Result(); + for (int i = 1; i < prices.length; i++) { + Result result = new Result(); + result.profit = prices[i] - prices[0]; + result.transactions = 1; + if (result.profit < 0) { + result.profit = 0; + result.transactions = 0; + } + for (int j = 1; j < i; j++) { + if (profits[j - 1].transactions + 1 > k) { + continue; + } + int profit = profits[j - 1].profit + prices[i] - prices[j]; + if (profit > result.profit) { + result.profit = profit; + result.transactions = profits[j - 1].transactions + 1; + } + } + if (profits[i - 1].profit > result.profit) { + result.profit = profits[i - 1].profit; + result.transactions = profits[i - 1].transactions; + } + profits[i] = result; + } + return profits[prices.length - 1].profit; + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/InterleavingString.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/InterleavingString.java new file mode 100644 index 0000000..6d03b21 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/InterleavingString.java @@ -0,0 +1,52 @@ +package org.wcong.test.algorithm.leetcode.string; + +/** + * Given s1, s2, s3 + * find whether s3 is formed by the interleaving of s1 and s2. + * For example, + * Given: + * s1 = "aabcc", + * s2 = "dbbca", + * When s3 = "aadbbcbcac", return true. + * When s3 = "aadbbbaccc", return false. + * + * @author wcong + * @since 15/06/2017 + */ +public class InterleavingString { + public boolean isInterleaveBruteForce(String s1, String s2, String s3) { + if (s1.length() + s2.length() != s3.length()) { + return false; + } + return isInterleaveBruteForce(s1, 0, s2, 0, s3, 0); + } + + private boolean isInterleaveBruteForce(String s1, int index1, String s2, int index2, String s3, int index3) { + return (index3 < s3.length() + && index1 < s1.length() + && s3.charAt(index3) == s1.charAt(index1) && + isInterleaveBruteForce(s1, index1 + 1, s2, index2, s3, index3 + 1)) + || (index3 < s3.length() + && index2 < s2.length() + && s3.charAt(index3) == s2.charAt(index2) + && isInterleaveBruteForce(s1, index1, s2, index2 + 1, s3, index3 + 1)) + || (index3 == s3.length() && index1 + index2 == s3.length()); + } + + public boolean isInterleaveDp(String s1, String s2, String s3) { + if (s1.length() + s2.length() != s3.length()) { + return false; + } + boolean[][] matchMatrix = new boolean[s1.length() + 1][s2.length() + 1]; + matchMatrix[0][0] = true; + matchMatrix[1][0] = s3.charAt(0) == s1.charAt(0); + matchMatrix[0][1] = s3.charAt(0) == s2.charAt(0); + for (int i = 1; i < s3.length(); i++) { + int length = i + 1; + for (int index1 = 0; index1 < length && index1 < s1.length() && length - index1 < s2.length(); index1++) { + matchMatrix[index1][length - index1] = s3.charAt(i) == s1.charAt(index1) && matchMatrix[index1][length - index1 - 1]; + } + } + return matchMatrix[s1.length()][s2.length()]; + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/KthSmallestLexicographicalOrder.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/KthSmallestLexicographicalOrder.java new file mode 100644 index 0000000..a8fa2da --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/KthSmallestLexicographicalOrder.java @@ -0,0 +1,67 @@ +package org.wcong.test.algorithm.leetcode.string; + +import java.util.Arrays; + +/** + * Given integers n and k + * find the lexicographically k-th smallest integer in the range from 1 to n. + * Note: 1 ≤ k ≤ n ≤ 10^9. + * Example: + * Input: n: 13 k: 2 + * Output:10 + * Explanation: + * The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], + * so the second smallest number is 10. + * + * @author wcong + * @since 05/06/2017 + */ +public class KthSmallestLexicographicalOrder { + + public int findKthNumberBruteForce(int n, int k) { + String[] numbers = new String[n]; + for (int i = 1; i <= n; i++) { + numbers[i - 1] = String.valueOf(i); + } + Arrays.sort(numbers); + return Integer.parseInt(numbers[k - 1]); + } + + public static class Result { + boolean found = false; + int number = 1; + int order = 1; + } + + public int findKthNumberGreed(int n, int k) { + Result result = new Result(); + findKthNumberGreed(n, k, result); + return result.number; + } + + private void findKthNumberGreed(int n, int k, Result result) { + int number = result.number; + if (result.found) { + return; + } + for (int i = 0; i < 9; i++) { + if (result.order < k && number * 10 <= n) { + result.number = number * 10; + result.order += 1; + result.found = result.order == k; + findKthNumberGreed(n, k, result); + } + if (result.found) { + return; + } + number += 1; + if (number > n) { + return; + } + result.order += 1; + result.number = number; + result.found = result.order == k; + } + } + +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/LongestValidParentheses.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/LongestValidParentheses.java new file mode 100644 index 0000000..5dbe8be --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/LongestValidParentheses.java @@ -0,0 +1,82 @@ +package org.wcong.test.algorithm.leetcode.string; + +import java.util.Stack; + +/** + * Given a string containing just the characters '(' and ')', + * find the length of the longest valid (well-formed) parentheses substring. + * For "(()", the longest valid parentheses substring is "()", which has length = 2. + * Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. + * + * @author wcong + * @since 03/06/2017 + */ +public class LongestValidParentheses { + public int longestValidParenthesesBruteForce(String s) { + if (s == null || s.length() == 0) { + return 0; + } + int maxLength = 0; + for (int start = 0; start < s.length(); start++) { + for (int end = start + 1; end < s.length(); end++) { + if (isValidParentheses(s, start, end)) { + int length = end - start + 1; + if (length > maxLength) { + maxLength = length; + } + } + } + } + return maxLength; + } + + private boolean isValidParentheses(String s, int start, int end) { + Stack characterStack = new Stack<>(); + for (int i = start; i <= end; i++) { + if (s.charAt(i) == '(') { + characterStack.push('('); + } else if (s.charAt(i) == ')' && !characterStack.isEmpty() && characterStack.peek() == '(') { + characterStack.pop(); + } else { + return false; + } + } + return characterStack.isEmpty(); + } + + public int longestValidParenthesesGreed(String s) { + int maxLength = 0; + int leftNum = 0; + int rightNum = 0; + int startIndex = 0; + Stack characterStack = new Stack<>(); + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '(') { + characterStack.push(i); + leftNum += 1; + } else { + if (characterStack.isEmpty()) { + leftNum = 0; + rightNum = 0; + startIndex = i + 1; + } else { + characterStack.peek(); + rightNum += 1; + characterStack.pop(); + if (characterStack.isEmpty()) { + int length = i - startIndex + 1; + if (length > maxLength) { + maxLength = length; + } + leftNum = 0; + rightNum = 0; + } + } + } + } + if (leftNum >= rightNum && rightNum * 2 > maxLength) { + maxLength = rightNum * 2; + } + return maxLength; + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/PalindromePartitioning2.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/PalindromePartitioning2.java new file mode 100644 index 0000000..ff9f155 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/PalindromePartitioning2.java @@ -0,0 +1,48 @@ +package org.wcong.test.algorithm.leetcode.string; + +/** + * Given a string s, + * partition s such that every substring of the partition is a palindrome. + * Return the minimum cuts needed for a palindrome partitioning of s. + * For example, given s = "aab", + * Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. + * + * @author wcong + * @since 07/06/2017 + */ +public class PalindromePartitioning2 { + + boolean[][] palindromeMatrix; + + public int minCutDp(String s) { + int[] minCut = new int[s.length()]; + palindromeMatrix = new boolean[s.length()][s.length()]; + minCut[0] = 0; + for (int i = 1; i < s.length(); i++) { + if (isPalindrome(s, 0, i)) { + minCut[i] = 0; + } else { + int minCutNum = minCut[i - 1] + 1; + for (int j = 1; j < i; j++) { + if (isPalindrome(s, j, i)) { + int cutNum = minCut[j - 1] + 1; + if (cutNum < minCutNum) { + minCutNum = cutNum; + } + } + } + minCut[i] = minCutNum; + } + } + return minCut[s.length() - 1]; + } + + private boolean isPalindrome(String s, int start, int end) { + if (s.charAt(start) == s.charAt(end) && (start + 1 >= end - 1 || palindromeMatrix[start + 1][end - 1])) { + palindromeMatrix[start][end] = true; + return true; + } else { + return false; + } + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/ShortestPalindrome.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/ShortestPalindrome.java new file mode 100644 index 0000000..35c5738 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/ShortestPalindrome.java @@ -0,0 +1,41 @@ +package org.wcong.test.algorithm.leetcode.string; + +/** + * Given a string S + * you are allowed to convert it to a palindrome by adding characters in front of it. + * Find and return the shortest palindrome you can find by performing this transformation. + * For example: + * Given "aacecaaa", return "aaacecaaa". + * Given "abcd", return "dcbabcd". + * + * @author wcong + * @since 07/06/2017 + */ +public class ShortestPalindrome { + + public String shortestPalindromeBruteForce(String s) { + StringBuilder insert = new StringBuilder(); + int end = s.length() - 1; + while (end > 0) { + if (isPalindrome(s, 0, end)) { + break; + } else { + insert.append(s.charAt(end)); + end -= 1; + } + } + return insert + s; + } + + private boolean isPalindrome(String s, int start, int end) { + while (start <= end) { + if (s.charAt(start) == s.charAt(end)) { + start += 1; + end -= 1; + } else { + return false; + } + } + return true; + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/StrongPassword.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/StrongPassword.java new file mode 100644 index 0000000..9788d58 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/StrongPassword.java @@ -0,0 +1,22 @@ +package org.wcong.test.algorithm.leetcode.string; + +/** + * A password is considered strong if below conditions are all met: + * 1. It has at least 6 characters and at most 20 characters. + * 2. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit. + * 3. It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met). + * Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0. + * Insertion, deletion or replace of any one character are all considered as one change. + * + * @author wcong + * @since 07/05/2017 + */ +public class StrongPassword { + + public int strongPasswordDP(String s) { + int[][] distance = new int[s.length()][s.length()]; + + return distance[s.length()][s.length()]; + } + +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/SubstringWithConcatenationAllWords.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/SubstringWithConcatenationAllWords.java new file mode 100644 index 0000000..097cc02 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/SubstringWithConcatenationAllWords.java @@ -0,0 +1,67 @@ +package org.wcong.test.algorithm.leetcode.string; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +/** + * You are given a string, s, and a list of words, words, + * that are all of the same length. + * Find all starting indices of substring(s) in s + * that is a concatenation of each word in words + * exactly once and without any intervening characters. + * For example, given: + * s: "barfoothefoobarman" + * words: ["foo", "bar"] + * You should return the indices: [0,9]. + * (order does not matter). + * + * @author wcong + * @since 17/05/2017 + */ +public class SubstringWithConcatenationAllWords { + + public List findSubstringBruteForce(String s, String[] words) { + List indices = new LinkedList<>(); + if (words == null || words.length == 0) { + return indices; + } + int len = words[0].length(); + Map map = new HashMap<>(); + for (String word : words) { + if (map.containsKey(word)) { + map.put(word, map.get(word) + 1); + } else { + map.put(word, 1); + } + } + for (int index = 0; index < s.length(); index++) { + if (isConcatenation(s, index, new HashMap<>(map), len)) { + indices.add(index); + } + } + return indices; + } + + private boolean isConcatenation(String s, int index, Map map, int len) { + if (map.isEmpty()) { + return true; + } + if (index + len > s.length()) { + return false; + } + String nextWord = s.substring(index, index + len); + Integer num = map.get(nextWord); + if (num == null) { + return false; + } + if (num == 1) { + map.remove(nextWord); + } else { + map.put(nextWord, num - 1); + } + return isConcatenation(s, index + len, map, len); + } + +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/TextJustifacation.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/TextJustifacation.java new file mode 100644 index 0000000..2f9657f --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/TextJustifacation.java @@ -0,0 +1,26 @@ +package org.wcong.test.algorithm.leetcode.string; + +import java.util.List; + +/** + * Given an array of words and a length L, + * format the text such that each line has exactly L characters and is fully (left and right) justified. + *

+ * You should pack your words in a greedy approach; + * that is, pack as many words as you can in each line. + * Pad extra spaces ' ' when necessary so that each line has exactly L characters. + *

+ * Extra spaces between words should be distributed as evenly as possible. + * If the number of spaces on a line do not divide evenly between words, + * the empty slots on the left will be assigned more spaces than the slots on the right. + *

+ * For the last line of text, it should be left justified and no extra space is inserted between words. + * + * @author wcong + * @since 05/05/2017 + */ +public class TextJustifacation { + public List fullJustify(String[] words, int maxWidth) { + return null; + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/WordBreak2.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/WordBreak2.java new file mode 100644 index 0000000..2ceb521 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/WordBreak2.java @@ -0,0 +1,89 @@ +package org.wcong.test.algorithm.leetcode.string; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, + * add spaces in s to construct a sentence where each word is a valid dictionary word. + * You may assume the dictionary does not contain duplicate words. + * Return all such possible sentences. + * For example, given + * s = "catsanddog", + * dict = ["cat", "cats", "and", "sand", "dog"]. + * A solution is ["cats and dog", "cat sand dog"]. + * + * @author wcong + * @since 24/05/2017 + */ +public class WordBreak2 { + + public List wordBreakBruteForce(String s, List wordDict) { + Set wordSet = new HashSet<>(); + for (String word : wordDict) { + wordSet.add(word); + } + List wordBreakList = new LinkedList<>(); + breakWord(s, wordSet, 0, "", wordBreakList); + return wordBreakList; + } + + public List wordBreakDp(String s, List wordDict) { + Set wordSet = new HashSet<>(); + int maxLength = 0; + for (String word : wordDict) { + wordSet.add(word); + if (word.length() > maxLength) { + maxLength = word.length(); + } + } + List> breakWordList = new ArrayList<>(s.length()); + List firstChar = new LinkedList<>(); + breakWordList.add(firstChar); + + Map> map = new HashMap<>(); + if (wordSet.contains(s.substring(0, 1))) { + firstChar.add(s.substring(0, 1)); + } + map.put(s.substring(0, 1),firstChar); + for (int index = 1; index < s.length(); index++) { + List currentList = new ArrayList<>(); + for (int last = index; last >= 0 && (index - last) < maxLength; last--) { + String tempString = s.substring(last, index + 1); + if (wordSet.contains(tempString)) { + if (last == 0) { + currentList.add(tempString); + } else { + List lastBreakList = breakWordList.get(last - 1); + for (String lastBreak : lastBreakList) { + currentList.add(lastBreak + " " + tempString); + } + } + } + } + breakWordList.add(currentList); + } + return breakWordList.get(s.length() - 1); + } + + private void breakWord(String s, Set wordSet, int index, String currentWord, List wordBreakList) { + if (index >= s.length()) { + wordBreakList.add(currentWord); + return; + } + for (int nextIndex = index; nextIndex < s.length(); nextIndex++) { + String tempString = s.substring(index, nextIndex + 1); + if (wordSet.contains(tempString)) { + String temp = currentWord.length() == 0 ? tempString : currentWord + " " + tempString; + breakWord(s, wordSet, nextIndex + 1, temp, wordBreakList); + } + } + } + +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/string/WordSearch2.java b/src/main/java/org/wcong/test/algorithm/leetcode/string/WordSearch2.java new file mode 100644 index 0000000..d6dcac5 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/string/WordSearch2.java @@ -0,0 +1,56 @@ +package org.wcong.test.algorithm.leetcode.string; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +/** + * Given a 2D board and a list of words from the dictionary, + * find all words in the board. + * Each word must be constructed from letters of sequentially adjacent cell, + * where "adjacent" cells are those horizontally or vertically neighboring. + * The same letter cell may not be used more than once in a word. + * For example, + * Given words = ["oath","pea","eat","rain"] and board = + * [ + * ['o','a','a','n'], + * ['e','t','a','e'], + * ['i','h','k','r'], + * ['i','f','l','v'] + * ] + * Return ["eat","oath"]. + * + * @author wcong + * @since 26/05/2017 + */ +public class WordSearch2 { + + public List findWords(char[][] board, String[] words) { + Map> characterListMap = new HashMap<>(); + for (int rowIndex = 0; rowIndex < board.length; rowIndex++) { + char[] row = board[rowIndex]; + for (int columnIndex = 0; columnIndex < row.length; columnIndex++) { + char column = row[columnIndex]; + List indexList = characterListMap.get(column); + if (indexList == null) { + indexList = new LinkedList<>(); + characterListMap.put(column, indexList); + } + int[] index = new int[2]; + index[0] = rowIndex; + index[1] = columnIndex; + indexList.add(index); + } + } + List wordList = new LinkedList<>(); + for (String word : words) { + List firstIndexList = characterListMap.get(word.charAt(0)); + if (firstIndexList == null) { + continue; + } + boolean contains = false; + } + return wordList; + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/tree/BinaryTreeMaximumSubPath.java b/src/main/java/org/wcong/test/algorithm/leetcode/tree/BinaryTreeMaximumSubPath.java new file mode 100644 index 0000000..21d5261 --- /dev/null +++ b/src/main/java/org/wcong/test/algorithm/leetcode/tree/BinaryTreeMaximumSubPath.java @@ -0,0 +1,41 @@ +package org.wcong.test.algorithm.leetcode.tree; + +/** + * Given a binary tree, find the maximum path sum. + * For this problem, + * a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. + * The path must contain at least one node and does not need to go through the root. + * + * @author wcong + * @since 05/05/2017 + */ +public class BinaryTreeMaximumSubPath { + + private int maxPath; + + public int maxPathSum(TreeNode root) { + maxPath = Integer.MIN_VALUE; + maxSubPathSum(root); + return maxPath; + } + + private int maxSubPathSum(TreeNode node) { + if (node == null) { + return 0; + } + int left = maxSubPathSum(node.left); + int right = maxSubPathSum(node.right); + int maxSum = node.val; + if (left > 0) { + maxSum += left; + } + if (right > 0) { + maxSum += right; + } + if (maxPath < maxSum) { + maxPath = maxSum; + } + int max = left > right ? left : right; + return max > 0 ? max + node.val : node.val; + } +} diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/tree/InorderSuccessorInBST.java b/src/main/java/org/wcong/test/algorithm/leetcode/tree/InorderSuccessorInBST.java index 50c477c..58534c8 100644 --- a/src/main/java/org/wcong/test/algorithm/leetcode/tree/InorderSuccessorInBST.java +++ b/src/main/java/org/wcong/test/algorithm/leetcode/tree/InorderSuccessorInBST.java @@ -17,7 +17,7 @@ public static TreeNode inOrderSuccessor(TreeNode root, TreeNode findNode) { TreeNode lastLeftNode = null; TreeNode compareNode = root; while (compareNode != null) { - if (findNode.value < compareNode.value) { + if (findNode.val < compareNode.val) { lastLeftNode = compareNode; compareNode = compareNode.left; } else { diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/tree/LowestCommonAncestorOfABinaryTree.java b/src/main/java/org/wcong/test/algorithm/leetcode/tree/LowestCommonAncestorOfABinaryTree.java index 8a047fe..5b27b0c 100644 --- a/src/main/java/org/wcong/test/algorithm/leetcode/tree/LowestCommonAncestorOfABinaryTree.java +++ b/src/main/java/org/wcong/test/algorithm/leetcode/tree/LowestCommonAncestorOfABinaryTree.java @@ -29,7 +29,7 @@ public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode node1, TreeN } private static boolean findNode(TreeNode treeNode, TreeNode findNode, List path) { - if (treeNode.value == findNode.value) { + if (treeNode.val == findNode.val) { return true; } else { if (treeNode.left != null) { diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/tree/SumOfLeftLeaves.java b/src/main/java/org/wcong/test/algorithm/leetcode/tree/SumOfLeftLeaves.java index aecf522..6bcffa2 100644 --- a/src/main/java/org/wcong/test/algorithm/leetcode/tree/SumOfLeftLeaves.java +++ b/src/main/java/org/wcong/test/algorithm/leetcode/tree/SumOfLeftLeaves.java @@ -25,7 +25,7 @@ public static int sumLeft(TreeNode root) { treeNodeStack.push(treeNode.right); } if (treeNode.left != null) { - sum += treeNode.left.value; + sum += treeNode.left.val; treeNodeStack.push(treeNode.left); } } diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/tree/TreeNode.java b/src/main/java/org/wcong/test/algorithm/leetcode/tree/TreeNode.java index ef339f1..bdb9ad8 100644 --- a/src/main/java/org/wcong/test/algorithm/leetcode/tree/TreeNode.java +++ b/src/main/java/org/wcong/test/algorithm/leetcode/tree/TreeNode.java @@ -5,10 +5,10 @@ */ public class TreeNode { - int value; + public int val; - TreeNode left; + public TreeNode left; - TreeNode right; + public TreeNode right; } diff --git a/src/main/java/org/wcong/test/algorithm/leetcode/tree/ValidateBinaryTree.java b/src/main/java/org/wcong/test/algorithm/leetcode/tree/ValidateBinaryTree.java index 74913e8..576bdd1 100644 --- a/src/main/java/org/wcong/test/algorithm/leetcode/tree/ValidateBinaryTree.java +++ b/src/main/java/org/wcong/test/algorithm/leetcode/tree/ValidateBinaryTree.java @@ -6,24 +6,24 @@ */ public class ValidateBinaryTree { - public static void main(String args) { - } + public static void main(String args) { + } - static int max = Integer.MIN_VALUE; + static int max = Integer.MIN_VALUE; - public static boolean validate(TreeNode treeNode) { - if (treeNode == null) { - return true; - } - if (!validate(treeNode.left)) { - return false; - } - if (treeNode.value >= max) { - max = treeNode.value; - } else { - return false; - } - return validate(treeNode.right); - } + public static boolean validate(TreeNode treeNode) { + if (treeNode == null) { + return true; + } + if (!validate(treeNode.left)) { + return false; + } + if (treeNode.val >= max) { + max = treeNode.val; + } else { + return false; + } + return validate(treeNode.right); + } } diff --git a/src/main/java/org/wcong/test/concurrent/Basic.java b/src/main/java/org/wcong/test/concurrent/Basic.java new file mode 100644 index 0000000..29e0c0c --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/Basic.java @@ -0,0 +1,63 @@ +package org.wcong.test.concurrent; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * @author wcong + * @since 29/04/2017 + */ +public class Basic { + + public static class MyThread extends Thread { + + private CountDownLatch countDownLatch; + + public MyThread(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + @Override + public void run() { + try { + countDownLatch.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("I'm running"); + } + } + + public static class MyRunner implements Runnable { + + private CountDownLatch countDownLatch; + + public MyRunner(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + @Override + public void run() { + try { + countDownLatch.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("I'm running too"); + } + } + + public static void main(String[] args) throws InterruptedException { + + CountDownLatch countDownLatch = new CountDownLatch(1); + Thread thread = new MyThread(countDownLatch); + thread.start(); + Thread secondThread = new Thread(new MyRunner(countDownLatch)); + secondThread.start(); + System.out.println("wait for it"); + thread.join(); + countDownLatch.countDown(); + TimeUnit.MILLISECONDS.sleep(1000); + } + +} diff --git a/src/main/java/org/wcong/test/concurrent/CountDownLatchThread.java b/src/main/java/org/wcong/test/concurrent/CountDownLatchThread.java new file mode 100644 index 0000000..dba2fa5 --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/CountDownLatchThread.java @@ -0,0 +1,27 @@ +package org.wcong.test.concurrent; + +import java.util.concurrent.CountDownLatch; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class CountDownLatchThread implements Runnable { + + private CountDownLatch countDownLatch; + + public CountDownLatchThread(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + public void run() { + System.out.println("wait for it"); + countDownLatch.countDown(); + try { + countDownLatch.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("start"); + } +} diff --git a/src/main/java/org/wcong/test/concurrent/CyclicBarrierPrint.java b/src/main/java/org/wcong/test/concurrent/CyclicBarrierPrint.java new file mode 100644 index 0000000..e3fec8a --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/CyclicBarrierPrint.java @@ -0,0 +1,38 @@ +package org.wcong.test.concurrent; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class CyclicBarrierPrint implements Runnable { + + private CyclicBarrier cyclicBarrier; + + public CyclicBarrierPrint(CyclicBarrier cyclicBarrier) { + this.cyclicBarrier = cyclicBarrier; + } + + @Override + public void run() { + System.out.println("I'm ready"); + try { + cyclicBarrier.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } + System.out.println("I'm ready 1"); + try { + cyclicBarrier.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } + System.out.println("we are finished"); + } +} diff --git a/src/main/java/org/wcong/test/concurrent/ExceptionHandler.java b/src/main/java/org/wcong/test/concurrent/ExceptionHandler.java new file mode 100644 index 0000000..f0cadd9 --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/ExceptionHandler.java @@ -0,0 +1,30 @@ +package org.wcong.test.concurrent; + +/** + * @author wcong + * @since 29/04/2017 + */ +public class ExceptionHandler { + + public static class MyThread extends Thread { + public void run() { + throw new RuntimeException("hello exception"); + } + } + + public static class MyExceptionHandler implements Thread.UncaughtExceptionHandler { + + @Override + public void uncaughtException(Thread t, Throwable e) { + System.out.println(e.toString()); + } + } + + public static void main(String[] args) { + MyThread myThread = new MyThread(); + myThread.setUncaughtExceptionHandler(new MyExceptionHandler()); + myThread.start(); + System.out.println("haha"); + } + +} diff --git a/src/main/java/org/wcong/test/concurrent/PhaserPrint.java b/src/main/java/org/wcong/test/concurrent/PhaserPrint.java new file mode 100644 index 0000000..4f22131 --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/PhaserPrint.java @@ -0,0 +1,30 @@ +package org.wcong.test.concurrent; + +import java.util.concurrent.Phaser; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class PhaserPrint implements Runnable { + + private Phaser phaser; + + public PhaserPrint(Phaser phaser) { + this.phaser = phaser; + } + + @Override + public void run() { + System.out.println("thread:" + Thread.currentThread().getId() + ":print 1"); + phaser.arriveAndAwaitAdvance(); + System.out.println("thread:" + Thread.currentThread().getId() + ":print 2"); + phaser.arriveAndAwaitAdvance(); + System.out.println("thread:" + Thread.currentThread().getId() + ":print 3"); + phaser.arriveAndAwaitAdvance(); + System.out.println("thread:" + Thread.currentThread().getId() + ":print 4"); + phaser.arriveAndAwaitAdvance(); + System.out.println("thread:" + Thread.currentThread().getId() + ":finished"); + phaser.arriveAndDeregister(); + } +} diff --git a/src/main/java/org/wcong/test/concurrent/ProducerAndComsumer.java b/src/main/java/org/wcong/test/concurrent/ProducerAndComsumer.java new file mode 100644 index 0000000..8148f42 --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/ProducerAndComsumer.java @@ -0,0 +1,46 @@ +package org.wcong.test.concurrent; + +import java.util.LinkedList; + +/** + * @author wcong + * @since 29/04/2017 + */ +public class ProducerAndComsumer { + + private static class Queue { + + private int maxSize; + + public Queue(int maxSize) { + this.maxSize = maxSize; + } + + LinkedList integerList = new LinkedList<>(); + + public synchronized Integer get() { + while (integerList.isEmpty()) { + try { + wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + return integerList.pop(); + + } + + public synchronized void add(Integer num) { + while (maxSize == integerList.size()) { + try { + wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + integerList.push(num); + } + + } + +} diff --git a/src/main/java/org/wcong/test/concurrent/SemaphorePrint.java b/src/main/java/org/wcong/test/concurrent/SemaphorePrint.java new file mode 100644 index 0000000..d50acc8 --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/SemaphorePrint.java @@ -0,0 +1,25 @@ +package org.wcong.test.concurrent; + +import java.util.concurrent.Semaphore; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class SemaphorePrint { + + private Semaphore semaphore = new Semaphore(2); + + public void print() { + try { + semaphore.acquire(); + System.out.println("acquire the semaphore :" + Thread.currentThread().getId() + ";"); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + System.out.println("release the semaphore :" + Thread.currentThread().getId() + ";"); + semaphore.release(); + } + } + +} diff --git a/src/main/java/org/wcong/test/concurrent/SynchronizedMethod.java b/src/main/java/org/wcong/test/concurrent/SynchronizedMethod.java new file mode 100644 index 0000000..ce0d666 --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/SynchronizedMethod.java @@ -0,0 +1,60 @@ +package org.wcong.test.concurrent; + +import java.util.LinkedList; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class SynchronizedMethod { + + LinkedList numList = new LinkedList<>(); + + public synchronized Integer get() { + System.out.println("Thread" + Thread.currentThread().getId() + "get the lock and sleep"); + try { + Thread.sleep(5000L); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return numList.pop(); + } + + public synchronized void push(Integer num) { + System.out.println("Thread" + Thread.currentThread().getId() + "get the lock and sleep"); + try { + Thread.sleep(5000L); + } catch (InterruptedException e) { + e.printStackTrace(); + } + numList.push(num); + } + + public static class MyGetThread extends Thread { + + private SynchronizedMethod synchronizedMethod; + + public MyGetThread(SynchronizedMethod synchronizedMethod) { + this.synchronizedMethod = synchronizedMethod; + } + + public void run() { + System.out.println("get " + synchronizedMethod.get()); + } + } + + public static class MyPutThread extends Thread { + + private SynchronizedMethod synchronizedMethod; + + public MyPutThread(SynchronizedMethod synchronizedMethod) { + this.synchronizedMethod = synchronizedMethod; + } + + public void run() { + synchronizedMethod.push(1); + System.out.println("put 1 "); + } + } + +} diff --git a/src/main/java/org/wcong/test/concurrent/ThreadWait.java b/src/main/java/org/wcong/test/concurrent/ThreadWait.java new file mode 100644 index 0000000..0a834a4 --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/ThreadWait.java @@ -0,0 +1,33 @@ +package org.wcong.test.concurrent; + +import java.util.concurrent.TimeUnit; + +/** + * @author wcong + * @since 29/04/2017 + */ +public class ThreadWait { + + public static class MyThread extends Thread { + public MyThread(String name) { + setName(name); + } + + public void run() { + TimeUnit.MILLISECONDS.toSeconds(1000); + System.out.println(getName()); + } + } + + public static void main(String[] args) throws InterruptedException { + MyThread thread1 = new MyThread("1"); + MyThread thread2 = new MyThread("2"); + thread1.start(); + thread2.start(); + thread1.join(); + thread2.join(); + System.out.println("finished"); + + } + +} diff --git a/src/main/java/org/wcong/test/concurrent/ThreadWithStop.java b/src/main/java/org/wcong/test/concurrent/ThreadWithStop.java new file mode 100644 index 0000000..33a5852 --- /dev/null +++ b/src/main/java/org/wcong/test/concurrent/ThreadWithStop.java @@ -0,0 +1,27 @@ +package org.wcong.test.concurrent; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class ThreadWithStop extends Thread { + + private boolean stop; + + public void setStop(boolean stop) { + this.stop = stop; + } + + public void run() { + while (!stop) { + try { + sleep(1000L); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("I'm running"); + } + System.out.println("I stopped"); + } + +} diff --git a/src/main/java/org/wcong/test/hackerrank/package-info.java b/src/main/java/org/wcong/test/hackerrank/package-info.java new file mode 100644 index 0000000..93dd5ef --- /dev/null +++ b/src/main/java/org/wcong/test/hackerrank/package-info.java @@ -0,0 +1 @@ +package org.wcong.test.hackerrank; \ No newline at end of file diff --git a/src/main/java/org/wcong/test/hackerrank/string/BearAndSteadyGene.java b/src/main/java/org/wcong/test/hackerrank/string/BearAndSteadyGene.java new file mode 100644 index 0000000..8a90365 --- /dev/null +++ b/src/main/java/org/wcong/test/hackerrank/string/BearAndSteadyGene.java @@ -0,0 +1,92 @@ +package org.wcong.test.hackerrank.string; + +import java.util.HashMap; +import java.util.Map; + +/** + * given a string consist of A,C,T,G + * if each of it appear 1/4 time the length it's steady + * give a string of length n divisible of 4; + * replace a minimum substring for it make it steady + *

+ * one loop get all num if + * + * @author wcong + * @since 03/05/2017 + */ +public class BearAndSteadyGene { + + public int minimumReplace(String s) { + int expectNum = s.length() / 4; + char[] charArray = new char[] { 'A', 'C', 'T', 'G' }; + Map characterIntegerMap = new HashMap<>(); + for (char soloChar : charArray) { + characterIntegerMap.put(soloChar, 0); + } + for (int index = 0; index < s.length(); index++) { + characterIntegerMap.put(s.charAt(index), characterIntegerMap.get(s.charAt(index)) + 1); + } + for (char soloChar : charArray) { + int count = characterIntegerMap.get(soloChar); + if (count <= expectNum) { + characterIntegerMap.remove(soloChar); + } else { + characterIntegerMap.put(soloChar, count - expectNum); + } + } + if (characterIntegerMap.isEmpty()) { + return 0; + } + Map encounterMap = new HashMap<>(); + for (char soloChar : characterIntegerMap.keySet()) { + encounterMap.put(soloChar, 0); + } + + int start = 0; + int index = 0; + int minSub = Integer.MAX_VALUE; + while (!characterIntegerMap.containsKey(s.charAt(index))) { + index += 1; + start = index; + } + while (index < s.length()) { + if (characterIntegerMap.containsKey(s.charAt(index))) { + encounterMap.put(s.charAt(index), encounterMap.get(s.charAt(index)) + 1); + } + int compare = compare(characterIntegerMap, encounterMap); + if (compare == 0) { + int sub = index - start+1; + if (sub < minSub) { + minSub = sub; + } + } else if (compare > 0) { + while (start < index) { + while (!characterIntegerMap.containsKey(s.charAt(index))) { + start += 1; + } + encounterMap.put(s.charAt(index), encounterMap.get(s.charAt(index)) - 1); + if (compare(characterIntegerMap, encounterMap) < 0) { + break; + } + start+=1; + } + } + index += 1; + } + return minSub; + } + + private int compare(Map characterIntegerMap, Map encounterMap) { + boolean isEqual = true; + for (Map.Entry characterIntegerEntry : characterIntegerMap.entrySet()) { + int encounter = encounterMap.get(characterIntegerEntry.getKey()); + if (encounter > characterIntegerEntry.getValue()) { + return 1; + } else if (encounter < characterIntegerEntry.getValue()) { + isEqual = false; + } + } + return isEqual ? 0 : -1; + } + +} diff --git a/src/main/java/org/wcong/test/hackerrank/string/PerfectString.java b/src/main/java/org/wcong/test/hackerrank/string/PerfectString.java new file mode 100644 index 0000000..03e2275 --- /dev/null +++ b/src/main/java/org/wcong/test/hackerrank/string/PerfectString.java @@ -0,0 +1,64 @@ +package org.wcong.test.hackerrank.string; + +import java.util.ArrayList; +import java.util.List; + +/** + * give a string consisting of a,b,c,d + * perfect string + * 1 num of a equal num of b + * 2 num of c equal num of d + * subsequent of string + * + * @author wcong + * @since 03/05/2017 + */ +public class PerfectString { + + public long perfectNum(String originString) { + int[] count = new int[4]; + for (char soloChar : originString.toCharArray()) { + count[soloChar - 'a'] += 1; + } + long perfectNum = 0; + long abNum = 0; + int minAb = count[0] < count[1] ? count[0] : count[1]; + for (int i = 1; i <= minAb; i++) { + abNum += combination(count[0], i) * combination(count[1], i); + } + perfectNum += abNum % 1000000007; + int minCD = count[2] < count[3] ? count[2] : count[3]; + long cdNum = 0; + for (int i = 1; i <= minCD; i++) { + cdNum += combination(count[2], i) * combination(count[3], i); + } + perfectNum += cdNum % 1000000007; + perfectNum = perfectNum % 1000000007; + perfectNum += (abNum * cdNum) % 1000000007; + perfectNum = perfectNum % 1000000007; + return perfectNum; + } + + static List factorialList = new ArrayList<>(); + + static { + factorialList.add(0); + factorialList.add(1); + } + + private int combination(int total, int num) { + if (total == 0 || num == 0) { + return 0; + } + if (total == num) { + return 1; + } + if (factorialList.size() - 1 < total) { + for (int currentNum = factorialList.size(); currentNum <= total; currentNum++) { + factorialList.add(factorialList.get(currentNum - 1) * currentNum); + } + } + return factorialList.get(total) / factorialList.get(total - num) / factorialList.get(num); + } + +} diff --git a/src/main/java/org/wcong/test/rxjava/MyPublisher.java b/src/main/java/org/wcong/test/rxjava/MyPublisher.java new file mode 100644 index 0000000..307c6cd --- /dev/null +++ b/src/main/java/org/wcong/test/rxjava/MyPublisher.java @@ -0,0 +1,120 @@ +package org.wcong.test.rxjava; + +import io.reactivex.Flowable; +import io.reactivex.FlowableSubscriber; +import io.reactivex.Scheduler; +import io.reactivex.functions.Consumer; +import io.reactivex.schedulers.Schedulers; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; + +public class MyPublisher { + + private static CountDownLatch countDownLatch = new CountDownLatch(4); + + public static void main(String[] args) throws InterruptedException { + new ParallelFlowableRange(1, 100, Schedulers.computation()).subscribe(new Consumer() { + @Override + public void accept(Integer integer) throws Exception { + System.out.println(Thread.currentThread().getName() + ":" + integer); + } + }); + countDownLatch.await(); + } + + + public static class ParallelFlowableRange extends Flowable { + + private Scheduler scheduler; + + private int start; + private int end; + + public ParallelFlowableRange(int start, int end, Scheduler scheduler) { + this.scheduler = scheduler; + this.start = start; + this.end = end; + } + + @Override + protected void subscribeActual(Subscriber subscriber) { + AtomicInteger atomicInteger = new AtomicInteger(start); + for (int i = 0; i < 4; i++) { + MySubscriber mySubscriber = new MySubscriber(subscriber, Integer.MAX_VALUE, scheduler.createWorker(), atomicInteger, end); + mySubscriber.onSubscribe(mySubscriber); + } + } + } + + public static class MySubscriber extends AtomicInteger implements FlowableSubscriber, Subscription, Runnable { + + private int prefetch; + private Scheduler.Worker worker; + private Subscriber actual; + private boolean cancel; + private AtomicInteger atomicInteger; + private int end; + + public MySubscriber(Subscriber actual, int prefetch, Scheduler.Worker worker, AtomicInteger atomicInteger, int end) { + this.actual = actual; + this.prefetch = prefetch; + this.worker = worker; + this.atomicInteger = atomicInteger; + this.end = end; + } + + @Override + public void onSubscribe(Subscription subscription) { + subscription.request(prefetch); + } + + @Override + public void onNext(Integer integer) { + actual.onNext(integer); + } + + @Override + public void onError(Throwable throwable) { + actual.onError(throwable); + } + + @Override + public void onComplete() { + countDownLatch.countDown(); + actual.onComplete(); + } + + @Override + public void request(long l) { + worker.schedule(this); + } + + @Override + public void cancel() { + cancel = true; + } + + @Override + public void run() { + while (true) { + if (cancel) { + break; + } + int num = atomicInteger.getAndIncrement(); + if (num < end) { + try { + onNext(num); + } catch (Exception e) { + onError(e); + } + } else { + onComplete(); + break; + } + } + } + } +} diff --git a/src/main/java/org/wcong/test/rxjava/package-info.java b/src/main/java/org/wcong/test/rxjava/package-info.java new file mode 100644 index 0000000..7b13049 --- /dev/null +++ b/src/main/java/org/wcong/test/rxjava/package-info.java @@ -0,0 +1,3 @@ +package org.wcong.test.rxjava; + +// about rxjava \ No newline at end of file diff --git a/src/test/java/org/wcong/test/concurrent/CountDownLatchThreadTest.java b/src/test/java/org/wcong/test/concurrent/CountDownLatchThreadTest.java new file mode 100644 index 0000000..20ad1ab --- /dev/null +++ b/src/test/java/org/wcong/test/concurrent/CountDownLatchThreadTest.java @@ -0,0 +1,31 @@ +package org.wcong.test.concurrent; + +import org.junit.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class CountDownLatchThreadTest { + + @Test + public void test() { + CountDownLatch countDownLatch = new CountDownLatch(10); + ExecutorService executorService = Executors.newFixedThreadPool(10); + for (int threadNum = 0; threadNum < 10; threadNum++) { + executorService.submit(new CountDownLatchThread(countDownLatch)); + } + executorService.shutdown(); + try { + executorService.awaitTermination(100000L, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/test/java/org/wcong/test/concurrent/CyclicBarrierPrintTest.java b/src/test/java/org/wcong/test/concurrent/CyclicBarrierPrintTest.java new file mode 100644 index 0000000..9f6e9d1 --- /dev/null +++ b/src/test/java/org/wcong/test/concurrent/CyclicBarrierPrintTest.java @@ -0,0 +1,41 @@ +package org.wcong.test.concurrent; + +import org.junit.Test; + +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class CyclicBarrierPrintTest { + + public static class CyclicBarrierMonitor implements Runnable { + + private int stage; + + @Override + public void run() { + System.out.println("we all are ready for stage :" + stage++); + } + } + + @Test + public void test() { + CyclicBarrier cyclicBarrier = new CyclicBarrier(10, new CyclicBarrierMonitor()); + ExecutorService executorService = Executors.newFixedThreadPool(10); + for (int threadNum = 0; threadNum < 10; threadNum++) { + executorService.submit(new CyclicBarrierPrint(cyclicBarrier)); + } + executorService.shutdown(); + try { + executorService.awaitTermination(10000L, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/test/java/org/wcong/test/concurrent/PhaserPrintTest.java b/src/test/java/org/wcong/test/concurrent/PhaserPrintTest.java new file mode 100644 index 0000000..e716615 --- /dev/null +++ b/src/test/java/org/wcong/test/concurrent/PhaserPrintTest.java @@ -0,0 +1,31 @@ +package org.wcong.test.concurrent; + +import org.junit.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Phaser; +import java.util.concurrent.TimeUnit; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class PhaserPrintTest { + + @Test + public void test() { + final Phaser phaser = new Phaser(10); // this will add to 10 emedialy,do not register again; + ExecutorService executorService = Executors.newFixedThreadPool(10); + for (int threadNum = 0; threadNum < 10; threadNum++) { + executorService.submit(new PhaserPrint(phaser)); + } + executorService.shutdown(); + try { + executorService.awaitTermination(10000L, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/test/java/org/wcong/test/concurrent/SemaphorePrintTest.java b/src/test/java/org/wcong/test/concurrent/SemaphorePrintTest.java new file mode 100644 index 0000000..2dbd7b2 --- /dev/null +++ b/src/test/java/org/wcong/test/concurrent/SemaphorePrintTest.java @@ -0,0 +1,44 @@ +package org.wcong.test.concurrent; + +import org.junit.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class SemaphorePrintTest { + + static class PrintRunner implements Runnable { + + private SemaphorePrint semaphorePrint; + + public PrintRunner(SemaphorePrint semaphorePrint) { + this.semaphorePrint = semaphorePrint; + } + + @Override + public void run() { + semaphorePrint.print(); + } + } + + @Test + public void test() { + SemaphorePrint semaphorePrint = new SemaphorePrint(); + ExecutorService executor = Executors.newFixedThreadPool(10); + for (int threadNum = 0; threadNum < 10; threadNum++) { + executor.submit(new PrintRunner(semaphorePrint)); + } + executor.shutdown(); + try { + executor.awaitTermination(10000L, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/test/java/org/wcong/test/concurrent/SynchronizedMethodTest.java b/src/test/java/org/wcong/test/concurrent/SynchronizedMethodTest.java new file mode 100644 index 0000000..6e16b98 --- /dev/null +++ b/src/test/java/org/wcong/test/concurrent/SynchronizedMethodTest.java @@ -0,0 +1,26 @@ +package org.wcong.test.concurrent; + +import org.junit.Test; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class SynchronizedMethodTest { + + @Test + public void test() { + SynchronizedMethod synchronizedMethod = new SynchronizedMethod(); + SynchronizedMethod.MyPutThread myPutThread = new SynchronizedMethod.MyPutThread(synchronizedMethod); + myPutThread.start(); + SynchronizedMethod.MyGetThread myGetThread = new SynchronizedMethod.MyGetThread(synchronizedMethod); + myGetThread.start(); + try { + myGetThread.join(); + myPutThread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/test/java/org/wcong/test/concurrent/ThreadWithStopTest.java b/src/test/java/org/wcong/test/concurrent/ThreadWithStopTest.java new file mode 100644 index 0000000..505e772 --- /dev/null +++ b/src/test/java/org/wcong/test/concurrent/ThreadWithStopTest.java @@ -0,0 +1,31 @@ +package org.wcong.test.concurrent; + +import org.junit.Test; + +import java.util.concurrent.TimeUnit; + +/** + * @author wcong + * @since 30/04/2017 + */ +public class ThreadWithStopTest { + + @Test + public void testStop() { + ThreadWithStop thread = new ThreadWithStop(); + thread.start(); + try { + TimeUnit.MILLISECONDS.sleep(5000L); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("i will set you stop"); + thread.setStop(true); + try { + thread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/test/java/org/wcong/test/hackerrank/package-info.java b/src/test/java/org/wcong/test/hackerrank/package-info.java new file mode 100644 index 0000000..93dd5ef --- /dev/null +++ b/src/test/java/org/wcong/test/hackerrank/package-info.java @@ -0,0 +1 @@ +package org.wcong.test.hackerrank; \ No newline at end of file diff --git a/src/test/java/org/wcong/test/hackerrank/string/BearAndSteadyGeneTest.java b/src/test/java/org/wcong/test/hackerrank/string/BearAndSteadyGeneTest.java new file mode 100644 index 0000000..8298e58 --- /dev/null +++ b/src/test/java/org/wcong/test/hackerrank/string/BearAndSteadyGeneTest.java @@ -0,0 +1,19 @@ +package org.wcong.test.hackerrank.string; + +import org.eclipse.core.runtime.Assert; +import org.junit.Test; + +/** + * @author wcong + * @since 04/05/2017 + */ +public class BearAndSteadyGeneTest { + + @Test + public void test() { + BearAndSteadyGene bearAndSteadyGene = new BearAndSteadyGene(); + Assert.isTrue(bearAndSteadyGene.minimumReplace("GAAATAAA") == 5); + + } + +} diff --git a/src/test/java/org/wcong/test/hackerrank/string/PerfectStringTest.java b/src/test/java/org/wcong/test/hackerrank/string/PerfectStringTest.java new file mode 100644 index 0000000..dab4d53 --- /dev/null +++ b/src/test/java/org/wcong/test/hackerrank/string/PerfectStringTest.java @@ -0,0 +1,21 @@ +package org.wcong.test.hackerrank.string; + +import org.eclipse.core.runtime.Assert; +import org.junit.Test; + +/** + * @author wcong + * @since 03/05/2017 + */ +public class PerfectStringTest { + + @Test + public void test() { + PerfectString perfectString = new PerfectString(); + Assert.isTrue(perfectString.perfectNum("abcd") == 3); + Assert.isTrue(perfectString.perfectNum("abc") == 1); + Assert.isTrue(perfectString.perfectNum("ddc") == 2); + Assert.isTrue(perfectString.perfectNum("dddccc") == 19); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/NumberToWordsTest.java b/src/test/java/org/wcong/test/leetcode/NumberToWordsTest.java new file mode 100644 index 0000000..f8c0f8b --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/NumberToWordsTest.java @@ -0,0 +1,22 @@ +package org.wcong.test.leetcode; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.numbers.NumberToWords; + +/** + * @author wcong + * @since 16/05/2017 + */ +public class NumberToWordsTest { + + @Test + public void testNumberToWords() { + NumberToWords numberToWords = new NumberToWords(); + Assert.assertTrue(numberToWords.numberToWords(123).equals("One Hundred Twenty Three")); + Assert.assertTrue(numberToWords.numberToWords(12345).equals("Twelve Thousand Three Hundred Forty Five")); + Assert.assertTrue(numberToWords.numberToWords(1234567) + .equals("One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven")); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/array/BestTimeBuySellStockIVTest.java b/src/test/java/org/wcong/test/leetcode/array/BestTimeBuySellStockIVTest.java new file mode 100644 index 0000000..c66f40f --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/array/BestTimeBuySellStockIVTest.java @@ -0,0 +1,28 @@ +package org.wcong.test.leetcode.array; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.string.BestTimeBuySellStockIV; + +/** + * @author wcong + * @since 10/06/2017 + */ +public class BestTimeBuySellStockIVTest { + + @Test + public void testMaxProfit() { + BestTimeBuySellStockIV solution = new BestTimeBuySellStockIV(); + int[] simple = new int[]{0, 1}; + int[] oneMax = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8}; + int[] transaction = new int[]{1, 2}; + int[] time = new int[]{48, 12, 60, 93, 97, 42, 25, 64, 17, 56, 85, 93, 9, 48, 52, 42, 58, 85, 81, 84, 69, 36, 1, 54, 23, 15, 72, 15, 11, 94}; + int[] border = new int[]{1, 4, 2}; + Assert.assertTrue(solution.maxProfitDp(2, simple) == 1); + Assert.assertTrue(solution.maxProfitDp(9, oneMax) == 8); + Assert.assertTrue(solution.maxProfitDp(1, transaction) == 1); + Assert.assertTrue(solution.maxProfitDp(2, border) == 3); + } + + +} diff --git a/src/test/java/org/wcong/test/leetcode/array/CandyTest.java b/src/test/java/org/wcong/test/leetcode/array/CandyTest.java new file mode 100644 index 0000000..8d8b4a6 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/array/CandyTest.java @@ -0,0 +1,23 @@ +package org.wcong.test.leetcode.array; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.array.Candy; + +/** + * @author wcong + * @since 19/06/2017 + */ +public class CandyTest { + + @Test + public void testCandies() { + Candy candy = new Candy(); + Assert.assertTrue(candy.candy(new int[]{11111}) == 1); + Assert.assertTrue(candy.candy(new int[]{1, 2, 2}) == 4); + Assert.assertTrue(candy.candy(new int[]{5, 4, 3, 2, 1, 0}) == 21); + Assert.assertTrue(candy.candy(new int[]{5, 4, 4, 2, 1, 0}) == 13); + Assert.assertTrue(candy.candy(new int[]{4, 2, 3, 4, 1}) == 9); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/array/CreateMaximumNumberTest.java b/src/test/java/org/wcong/test/leetcode/array/CreateMaximumNumberTest.java new file mode 100644 index 0000000..ff9720e --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/array/CreateMaximumNumberTest.java @@ -0,0 +1,38 @@ +package org.wcong.test.leetcode.array; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.array.CreateMaximumNumber; + +import java.util.Arrays; + +/** + * @author wcong + * @since 13/06/2017 + */ +public class CreateMaximumNumberTest { + + @Test + public void testMaxNumber() { + + CreateMaximumNumber solution = new CreateMaximumNumber(); + int[] e3nums1 = new int[]{3, 9}; + int[] e3nums2 = new int[]{8, 9}; + int[] e3result = new int[]{9, 8, 9}; + Assert.assertTrue(Arrays.equals(solution.maxNumberGreed(e3nums1, e3nums2, 3), e3result)); + int[] e1nums1 = new int[]{3, 4, 6, 5}; + int[] e1nums2 = new int[]{9, 1, 2, 5, 8, 3}; + int[] e1result = new int[]{9, 8, 6, 5, 3}; + Assert.assertTrue(Arrays.equals(solution.maxNumberGreed(e1nums1, e1nums2, 5), e1result)); + int[] e2nums1 = new int[]{6, 7}; + int[] e2nums2 = new int[]{6, 0, 4}; + int[] e2result = new int[]{6, 7, 6, 0, 4}; + Assert.assertTrue(Arrays.equals(solution.maxNumberGreed(e2nums1, e2nums2, 5), e2result)); + try { + throw new NoClassDefFoundError(); + } catch (Error e) { + e.printStackTrace(); + } + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/array/MaxPointsOnALineTest.java b/src/test/java/org/wcong/test/leetcode/array/MaxPointsOnALineTest.java new file mode 100644 index 0000000..4d760e2 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/array/MaxPointsOnALineTest.java @@ -0,0 +1,33 @@ +package org.wcong.test.leetcode.array; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.array.MaxPointsOnALine; + +/** + * @author wcong + * @since 10/05/2017 + */ +public class MaxPointsOnALineTest { + + @Test + public void testMaxPoints() { + MaxPointsOnALine maxPointsOnALine = new MaxPointsOnALine(); + MaxPointsOnALine.Point[] points = new MaxPointsOnALine.Point[] { new MaxPointsOnALine.Point(0, 0), + new MaxPointsOnALine.Point(1, 1), new MaxPointsOnALine.Point(2, 2), new MaxPointsOnALine.Point(1, 0), + new MaxPointsOnALine.Point(2, 0) }; + MaxPointsOnALine.Point[] points1 = new MaxPointsOnALine.Point[] { new MaxPointsOnALine.Point(0, 0), + new MaxPointsOnALine.Point(1, 1), new MaxPointsOnALine.Point(0, 0) }; + MaxPointsOnALine.Point[] points2 = new MaxPointsOnALine.Point[] { new MaxPointsOnALine.Point(1, 1),new MaxPointsOnALine.Point(1, 1), + new MaxPointsOnALine.Point(2, 2) , new MaxPointsOnALine.Point(2, 2) }; + //[-4,1],[-7,7],[-1,5],[9,-25] + MaxPointsOnALine.Point[] points3 = new MaxPointsOnALine.Point[] { new MaxPointsOnALine.Point(-4, 1),new MaxPointsOnALine.Point(-7, 7), + new MaxPointsOnALine.Point(-1, 5) , new MaxPointsOnALine.Point(9, -25) }; + Assert.assertTrue(maxPointsOnALine.maxPointsBruteForce(points) == 3); + Assert.assertTrue(maxPointsOnALine.maxPointsDp(points) == 3); + Assert.assertTrue(maxPointsOnALine.maxPointsDp(points1) == 3); + Assert.assertTrue(maxPointsOnALine.maxPointsDp(points2) == 4); + Assert.assertTrue(maxPointsOnALine.maxPointsDp(points3) == 3); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/array/MedianOfTwoSortedArrayTest.java b/src/test/java/org/wcong/test/leetcode/array/MedianOfTwoSortedArrayTest.java new file mode 100644 index 0000000..83a2cb5 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/array/MedianOfTwoSortedArrayTest.java @@ -0,0 +1,20 @@ +package org.wcong.test.leetcode.array; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.array.MedianOfTwoSortedArray; + +/** + * @author wcong + * @since 11/05/2017 + */ +public class MedianOfTwoSortedArrayTest { + + @Test + public void testFindMedianSortedArrays() { + MedianOfTwoSortedArray medianOfTwoSortedArray = new MedianOfTwoSortedArray(); + Assert.assertTrue(medianOfTwoSortedArray.findMedianSortedArrays(new int[] { 1, 3 }, new int[] { 2 }) == 2); + Assert.assertTrue(medianOfTwoSortedArray.findMedianSortedArrays(new int[] { 1, 3 }, new int[] { 3, 4 }) == 2.5); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/array/NUmbersOfIslandsTest.java b/src/test/java/org/wcong/test/leetcode/array/NUmbersOfIslandsTest.java new file mode 100644 index 0000000..4a60777 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/array/NUmbersOfIslandsTest.java @@ -0,0 +1,24 @@ +package org.wcong.test.leetcode.array; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.array.NumbersOfIslands; + +/** + * @author wcong + * @since 09/05/2017 + */ +public class NUmbersOfIslandsTest { + + @Test + public void testNumIslandsBruteForce() { + NumbersOfIslands numbersOfIslands = new NumbersOfIslands(); + char[][] chars1 = new char[][] { "11110".toCharArray(), "11010".toCharArray(), "11000".toCharArray(), + "00000".toCharArray() }; + Assert.assertTrue(numbersOfIslands.numIslandsBruteForce(chars1) == 1); + char[][] chars2 = new char[][] { "11000".toCharArray(), "11000".toCharArray(), "00100".toCharArray(), + "00011".toCharArray() }; + Assert.assertTrue(numbersOfIslands.numIslandsBruteForce(chars2) == 3); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/package-info.java b/src/test/java/org/wcong/test/leetcode/package-info.java new file mode 100644 index 0000000..6c0fd94 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/package-info.java @@ -0,0 +1 @@ +package org.wcong.test.leetcode; \ No newline at end of file diff --git a/src/test/java/org/wcong/test/leetcode/string/InterleavingStringTest.java b/src/test/java/org/wcong/test/leetcode/string/InterleavingStringTest.java new file mode 100644 index 0000000..245ba95 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/string/InterleavingStringTest.java @@ -0,0 +1,24 @@ +package org.wcong.test.leetcode.string; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.string.InterleavingString; + +/** + * @author wcong + * @since 15/06/2017 + */ +public class InterleavingStringTest { + + @Test + public void testIsInterleave() { + String s1 = "aabcc"; + String s2 = "dbbca"; + String s3 = "aadbbcbcac"; + String s4 = "aadbbbaccc"; + InterleavingString solution = new InterleavingString(); + Assert.assertTrue(solution.isInterleaveBruteForce(s1, s2, s3)); + Assert.assertTrue(!solution.isInterleaveBruteForce(s1, s2, s4)); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/string/KthSmallestLexicographicalOrderTest.java b/src/test/java/org/wcong/test/leetcode/string/KthSmallestLexicographicalOrderTest.java new file mode 100644 index 0000000..55b26c3 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/string/KthSmallestLexicographicalOrderTest.java @@ -0,0 +1,24 @@ +package org.wcong.test.leetcode.string; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.string.KthSmallestLexicographicalOrder; + +/** + * @author wcong + * @since 06/06/2017 + */ +public class KthSmallestLexicographicalOrderTest { + + + @Test + public void testFindKthNumber() { + KthSmallestLexicographicalOrder solution = new KthSmallestLexicographicalOrder(); + Assert.assertTrue(solution.findKthNumberBruteForce(13, 2) == 10); + Assert.assertTrue(solution.findKthNumberGreed(13, 2) == 10); + Assert.assertTrue(solution.findKthNumberGreed(132, 4) == 101); + Assert.assertTrue(solution.findKthNumberGreed(10, 3) == 2); + Assert.assertTrue(solution.findKthNumberGreed(1000, 1000) == 9999); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/string/LongestValidParenthesesTest.java b/src/test/java/org/wcong/test/leetcode/string/LongestValidParenthesesTest.java new file mode 100644 index 0000000..5aa3e6c --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/string/LongestValidParenthesesTest.java @@ -0,0 +1,31 @@ +package org.wcong.test.leetcode.string; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.string.LongestValidParentheses; + +/** + * @author wcong + * @since 03/06/2017 + */ +public class LongestValidParenthesesTest { + + @Test + public void testLongestValidParentheses() { + String s1 = "(()"; + String s2 = ")()())"; + String s3 = ")()()))()()()(())"; + String s4 = "()(()"; + String s5 = "(()(((()"; + LongestValidParentheses solution = new LongestValidParentheses(); + Assert.assertTrue(solution.longestValidParenthesesBruteForce(s1) == 2); + Assert.assertTrue(solution.longestValidParenthesesBruteForce(s2) == 4); + Assert.assertTrue(solution.longestValidParenthesesBruteForce(s3) == 10); + Assert.assertTrue(solution.longestValidParenthesesGreed(s1) == 2); + Assert.assertTrue(solution.longestValidParenthesesGreed(s2) == 4); + Assert.assertTrue(solution.longestValidParenthesesGreed(s3) == 10); + Assert.assertTrue(solution.longestValidParenthesesGreed(s4) == 2); + Assert.assertTrue(solution.longestValidParenthesesGreed(s5) == 2); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/string/PalindromePartitioning2Test.java b/src/test/java/org/wcong/test/leetcode/string/PalindromePartitioning2Test.java new file mode 100644 index 0000000..e24a894 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/string/PalindromePartitioning2Test.java @@ -0,0 +1,21 @@ +package org.wcong.test.leetcode.string; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.string.PalindromePartitioning2; + +/** + * @author wcong + * @since 07/06/2017 + */ +public class PalindromePartitioning2Test { + + @Test + public void testMinCutBruteForceDp() { + PalindromePartitioning2 solution = new PalindromePartitioning2(); + Assert.assertTrue(solution.minCutDp("aab") == 1); + Assert.assertTrue(solution.minCutDp("daa") == 1); + Assert.assertTrue(solution.minCutDp("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 1); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/string/ReversePiarsTest.java b/src/test/java/org/wcong/test/leetcode/string/ReversePiarsTest.java new file mode 100644 index 0000000..1d2cf36 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/string/ReversePiarsTest.java @@ -0,0 +1,25 @@ +package org.wcong.test.leetcode.string; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.array.ReversePairs; + +/** + * @author wcong + * @since 04/05/2017 + */ +public class ReversePiarsTest { + + @Test + public void test() { + int[] nums = new int[] { 1, 3, 4, 6, 8, 2 }; + int[] maxInt = new int[] { 2147483647, 2147483647, 2147483647, 2147483647, 2147483647, 2147483647 }; + ReversePairs reversePairs = new ReversePairs(); + Assert.assertTrue(reversePairs.reversePairsBruteForce(nums) == 2); + Assert.assertTrue(reversePairs.reversePairsDivideAndConquer(nums) == 2); + Assert.assertTrue(reversePairs.reversePairsDivideAndConquer(maxInt) == 0); + Assert.assertTrue(reversePairs.reversePairsLiner(new int[] { 1, 3, 4, 6, 8, 2 }) == 2); + Assert.assertTrue(reversePairs.reversePairsLiner(maxInt) == 0); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/string/ShortestPalindromeTest.java b/src/test/java/org/wcong/test/leetcode/string/ShortestPalindromeTest.java new file mode 100644 index 0000000..339a190 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/string/ShortestPalindromeTest.java @@ -0,0 +1,20 @@ +package org.wcong.test.leetcode.string; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.string.ShortestPalindrome; + +/** + * @author wcong + * @since 07/06/2017 + */ +public class ShortestPalindromeTest { + + @Test + public void testShortestPalindrome() { + ShortestPalindrome solution = new ShortestPalindrome(); + Assert.assertTrue(solution.shortestPalindromeBruteForce("aacecaaa").equals("aaacecaaa")); + Assert.assertTrue(solution.shortestPalindromeBruteForce("abcd").equals("dcbabcd")); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/string/SubstringWithConcatenationAllWordsTest.java b/src/test/java/org/wcong/test/leetcode/string/SubstringWithConcatenationAllWordsTest.java new file mode 100644 index 0000000..9919d80 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/string/SubstringWithConcatenationAllWordsTest.java @@ -0,0 +1,23 @@ +package org.wcong.test.leetcode.string; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.string.SubstringWithConcatenationAllWords; + +import java.util.Arrays; + +/** + * @author wcong + * @since 17/05/2017 + */ +public class SubstringWithConcatenationAllWordsTest { + + @Test + public void testFindSubstring() { + SubstringWithConcatenationAllWords test = new SubstringWithConcatenationAllWords(); + Assert.assertTrue(test.findSubstringBruteForce("barfoothefoobarman", new String[] { "foo", "bar" }) + .containsAll(Arrays.asList(0, 9))); + + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/string/WordBreak2Test.java b/src/test/java/org/wcong/test/leetcode/string/WordBreak2Test.java new file mode 100644 index 0000000..90b0bbe --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/string/WordBreak2Test.java @@ -0,0 +1,31 @@ +package org.wcong.test.leetcode.string; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.string.WordBreak2; + +import java.util.Arrays; +import java.util.List; + +/** + * @author wcong + * @since 24/05/2017 + */ +public class WordBreak2Test { + + @Test + public void testWordBreak2() { + List dict = Arrays.asList("cat", "cats", "and", "sand", "dog"); + WordBreak2 wordBreak2 = new WordBreak2(); + List result = wordBreak2.wordBreakBruteForce("catsanddog", dict); + Assert.assertTrue(result.get(0).equals("cat sand dog")); + Assert.assertTrue(result.get(1).equals("cats and dog")); + List resultDp = wordBreak2.wordBreakDp("catsanddog", dict); + Assert.assertTrue(resultDp.get(1).equals("cat sand dog")); + Assert.assertTrue(resultDp.get(0).equals("cats and dog")); + List dictNone = Arrays.asList("aaaa", "aa"); + List resultDpNone = wordBreak2.wordBreakDp("aaaaaaa", dictNone); + Assert.assertTrue(resultDpNone.isEmpty()); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/string/WordSearch2Test.java b/src/test/java/org/wcong/test/leetcode/string/WordSearch2Test.java new file mode 100644 index 0000000..7db6321 --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/string/WordSearch2Test.java @@ -0,0 +1,27 @@ +package org.wcong.test.leetcode.string; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.string.WordSearch2; + +import java.util.List; + +/** + * @author wcong + * @since 26/05/2017 + */ +public class WordSearch2Test { + + @Test + public void testWordSearch2() { + char[][] board = new char[][]{{'o', 'a', 'a', 'n'}, + {'e', 't', 'a', 'e'}, + {'i', 'h', 'k', 'r'}, + {'i', 'f', 'l', 'v'}}; + WordSearch2 wordSearch2 = new WordSearch2(); + List result = wordSearch2.findWords(board, new String[]{"oath", "pea", "eat", "rain"}); + Assert.assertTrue(result.get(0).equals("oath")); + Assert.assertTrue(result.get(1).equals("eat")); + } + +} diff --git a/src/test/java/org/wcong/test/leetcode/tree/BinaryTreeMaximumSubPathTest.java b/src/test/java/org/wcong/test/leetcode/tree/BinaryTreeMaximumSubPathTest.java new file mode 100644 index 0000000..ba5836a --- /dev/null +++ b/src/test/java/org/wcong/test/leetcode/tree/BinaryTreeMaximumSubPathTest.java @@ -0,0 +1,28 @@ +package org.wcong.test.leetcode.tree; + +import org.junit.Assert; +import org.junit.Test; +import org.wcong.test.algorithm.leetcode.tree.BinaryTreeMaximumSubPath; +import org.wcong.test.algorithm.leetcode.tree.TreeNode; + +/** + * @author wcong + * @since 05/05/2017 + */ +public class BinaryTreeMaximumSubPathTest { + + @Test + public void test() { + BinaryTreeMaximumSubPath maximumSubPath = new BinaryTreeMaximumSubPath(); + TreeNode treeNode = new TreeNode(); + treeNode.val = 1; + TreeNode left = new TreeNode(); + left.val = 2; + treeNode.left = left; + TreeNode right = new TreeNode(); + right.val = 3; + treeNode.right = right; + Assert.assertTrue(maximumSubPath.maxPathSum(treeNode) == 6); + } + +} diff --git a/src/test/java/org/wcong/test/package-info.java b/src/test/java/org/wcong/test/package-info.java new file mode 100644 index 0000000..45f186d --- /dev/null +++ b/src/test/java/org/wcong/test/package-info.java @@ -0,0 +1 @@ +package org.wcong.test; \ No newline at end of file