├── LeetCode ├── 3sum-closest │ └── Main.java ├── 3sum │ └── Main.java ├── 4sum │ └── Main.java ├── Minimum Depth of Binary Tree │ └── Main.java ├── README.md ├── add-binary │ └── Main.java ├── add-two-numbers │ └── Main.java ├── anagrams │ └── Main.java ├── balanced-binary-tree │ └── Main.java ├── best-time-to-buy-and-sell-stock-ii │ └── Main.java ├── best-time-to-buy-and-sell-stock-iii │ └── Main.java ├── best-time-to-buy-and-sell-stock │ └── Main.java ├── binary-tree-inorder-traversal │ └── Main.java ├── binary-tree-level-order-traversal-ii │ └── Main.java ├── binary-tree-level-order-traversal │ └── Main.java ├── binary-tree-maximum-path-sum │ └── Main.java ├── binary-tree-postorder-traversal │ └── Main.java ├── binary-tree-preorder-traversal │ └── Main.java ├── binary-tree-zigzag-level-order-traversal │ └── Main.java ├── candy │ └── Main.java ├── climbing-stairs │ └── Main.java ├── clone-graph │ └── Main.java ├── combination-sum-ii │ └── Main.java ├── combination-sum │ └── Main.java ├── combinations │ └── Main.java ├── construct-binary-tree-from-inorder-and-postorder-traversal │ └── Main.java ├── construct-binary-tree-from-preorder-and-inorder-traversal │ └── Main.java ├── container-with-most-water │ └── Main.java ├── convert-sorted-array-to-binary-search-tree │ └── Main.java ├── convert-sorted-list-to-binary-search-tree │ └── Main.java ├── copy-list-with-random-pointer │ └── Main.java ├── count-and-say │ └── Main.java ├── decode-ways │ └── Main.java ├── distinct-subsequences │ └── Main.java ├── divide-two-integers │ └── Main.java ├── edit-distance │ └── Main.java ├── evaluate-reverse-polish-notation │ └── Main.java ├── first-missing-positive │ └── Main.java ├── gas-station │ └── Main.java ├── generate-parentheses │ └── Main.java ├── gray-code │ └── Main.java ├── implement-strstr │ └── Main.java ├── insert-interval │ └── Main.java ├── insertion-sort-list │ └── Main.java ├── integer-to-roman │ └── Main.java ├── interleaving-string │ └── Main.java ├── jump-game-ii │ └── Main.java ├── jump-game │ └── Main.java ├── largest-rectangle-in-histogram │ └── Main.java ├── length-of-last-word │ └── Main.java ├── letter-combinations-of-a-phone-number │ └── Main.java ├── linked-list-cycle-ii │ └── Main.java ├── linked-list-cycle │ └── Main.java ├── longest-common-prefix │ └── Main.java ├── longest-consecutive-sequence │ └── Main.java ├── longest-palindromic-substring │ └── Main.java ├── longest-substring-without-repeating-characters │ └── Main.java ├── longest-valid-parentheses │ └── Main.java ├── max-points-on-a-line │ └── Main.java ├── maximal-rectangle │ └── Main.java ├── maximum-depth-of-binary-tree │ └── Main.java ├── maximum-subarray │ └── Main.java ├── median-of-two-sorted-arrays │ └── Main.java ├── merge-intervals │ └── Main.java ├── merge-k-sorted-lists │ └── Main.java ├── merge-sorted-array │ └── Main.java ├── merge-two-sorted-lists │ └── Main.java ├── minimum-path-sum │ └── Main.java ├── minimum-window-substring │ └── Main.java ├── multiply-strings │ └── Main.java ├── n-queens-ii │ └── Main.java ├── n-queens │ └── Main.java ├── next-permutation │ └── Main.java ├── palindrome-number │ └── Main.java ├── palindrome-partitioning-ii │ └── Main.java ├── palindrome-partitioning │ └── Main.java ├── partition-list │ └── Main.java ├── pascals-triangle-ii │ └── Main.java ├── pascals-triangle │ └── Main.java ├── path-sum-ii │ └── Main.java ├── path-sum │ └── Main.java ├── permutation-sequence │ └── Main.java ├── permutations-ii │ └── Main.java ├── permutations │ └── Main.java ├── plus-one │ └── Main.java ├── populating-next-right-pointers-in-each-node-ii │ └── Main.java ├── populating-next-right-pointers-in-each-node │ └── Main.java ├── powx-n │ └── Main.java ├── recover-binary-search-tree │ └── Main.java ├── regular-expression-matching │ └── Main.java ├── remove-duplicates-from-sorted-array-ii │ └── Main.java ├── remove-duplicates-from-sorted-array │ └── Main.java ├── remove-duplicates-from-sorted-list-ii │ └── Main.java ├── remove-duplicates-from-sorted-list │ └── Main.java ├── remove-element │ └── Main.java ├── remove-nth-node-from-end-of-list │ └── Main.java ├── reorder-list │ └── Main.java ├── restore-ip-addresses │ └── Main.java ├── reverse-integer │ └── Main.java ├── reverse-linked-list-ii │ └── Main.java ├── reverse-nodes-in-k-group │ └── Main.java ├── roman-to-integer │ └── Main.java ├── rotate-image │ └── Main.java ├── rotate-list │ └── Main.java ├── same-tree │ └── Main.java ├── scramble-string │ └── Main.java ├── search-a-2d-matrix │ └── Main.java ├── search-for-a-range │ └── Main.java ├── search-in-rotated-sorted-array-ii │ └── Main.java ├── search-in-rotated-sorted-array │ └── Main.java ├── search-insert-position │ └── Main.java ├── set-matrix-zeroes │ └── Main.java ├── simplify-path │ └── Main.java ├── single-number-ii │ └── Main.java ├── single-number │ └── Main.java ├── sort-colors │ └── Main.java ├── sort-list │ └── Main.java ├── spiral-matrix-ii │ └── Main.java ├── spiral-matrix │ └── Main.java ├── sqrtx │ └── Main.java ├── string-to-integer-atoi │ └── Main.java ├── subsets-ii │ └── Main.java ├── subsets │ └── Main.java ├── substring-with-concatenation-of-all-words │ └── Main.java ├── sudoku-solver │ └── Main.java ├── sum-root-to-leaf-numbers │ └── Main.java ├── surrounded-regions │ └── Main.java ├── swap-nodes-in-pairs │ └── Main.java ├── symmetric-tree │ └── Main.java ├── text-justification │ └── Main.java ├── trapping-rain-water │ └── Main.java ├── triangle │ └── Main.java ├── two-sum │ └── Main.java ├── unique-binary-search-trees-ii │ └── Main.java ├── unique-binary-search-trees │ └── Main.java ├── unique-paths-ii │ └── Main.java ├── unique-paths │ └── Main.java ├── valid-number │ └── Main.java ├── valid-palindrome │ └── Main.java ├── valid-parentheses │ └── Main.java ├── valid-sudoku │ └── Main.java ├── validate-binary-search-tree │ └── Main.java ├── wildcard-matching │ └── Main.java ├── word-break-ii │ └── Main.java ├── word-break │ └── Main.java ├── word-ladder-ii │ └── Main.java ├── word-ladder │ └── Main.java ├── word-search │ └── Main.java └── zigzag-conversion │ └── Main.java └── README.md /LeetCode/3sum-closest/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 4 | For example, given array S = {-1 2 1 -4}, and target = 1. 5 | 6 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 7 | import java.util.*; 8 | public class Solution { 9 | public int threeSumClosest(int[] num, int target) { 10 | if (num == null || num.length <= 2){ 11 | return target; 12 | } 13 | Arrays.sort(num); 14 | int n = num.length; 15 | int ans = num[0] + num[1] + num[2]; 16 | for(int i = 0;i= 1 && num[i] == num[i-1]){ 18 | continue; 19 | } 20 | int l = i + 1; 21 | int r = n - 1; 22 | while(l < r){ 23 | int sum = num[l] + num[r] + num[i]; 24 | if (Math.abs(sum - target) < Math.abs(ans - target)){ 25 | ans = sum; 26 | } 27 | boolean flag = false; 28 | if (Math.abs(num[l+1] + num[r] + num[i] - target) < Math.abs(num[l] + num[r-1] + num[i] - target)){ 29 | flag = true; 30 | } 31 | if (flag){ 32 | l++; 33 | }else{ 34 | r--; 35 | } 36 | } 37 | } 38 | return ans; 39 | } 40 | } -------------------------------------------------------------------------------- /LeetCode/3sum/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 4 | import java.util.*; 5 | public class Solution { 6 | public ArrayList> threeSum(int[] num) { 7 | ArrayList> ret = new ArrayList>(); 8 | if (num == null || num.length <= 2){ 9 | return ret; 10 | } 11 | Arrays.sort(num); 12 | int n = num.length; 13 | for(int i = 0;i= 1 && num[i] == num[i-1]){ 15 | continue; 16 | } 17 | int l = i + 1; 18 | int r = n - 1; 19 | while(l < r){ 20 | int sum = num[l] + num[r] + num[i]; 21 | if (sum == 0){ 22 | ArrayList list = new ArrayList(); 23 | list.add(num[i]); 24 | list.add(num[l]); 25 | list.add(num[r]); 26 | ret.add(new ArrayList<>(list)); 27 | l++;r--; 28 | while(l < r && num[l] == num[l-1]){ 29 | l++; 30 | } 31 | while(l < r && num[r] == num[r+1]){ 32 | r--; 33 | } 34 | }else if (sum < 0){ 35 | l++; 36 | }else{ 37 | r--; 38 | } 39 | } 40 | } 41 | return ret; 42 | } 43 | } -------------------------------------------------------------------------------- /LeetCode/4sum/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. 4 | Note: 5 | Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) 6 | The solution set must not contain duplicate quadruplets. 7 | 8 | For example, given array S = {1 0 -1 0 -2 2}, and target = 0. 9 | 10 | A solution set is: 11 | (-1, 0, 0, 1) 12 | (-2, -1, 1, 2) 13 | (-2, 0, 0, 2) 14 | 15 | import java.util.*; 16 | public class Solution { 17 | public ArrayList> fourSum(int[] num, int target) { 18 | ArrayList> ret = new ArrayList>(); 19 | if (num == null || num.length <= 3){ 20 | return ret; 21 | } 22 | Arrays.sort(num); 23 | int n = num.length; 24 | for(int i = 0;i= 1 && num[i] == num[i-1]){ 26 | continue; 27 | } 28 | for(int t = i+1;t= i+2 && num[t] == num[t-1]){ 30 | continue; 31 | } 32 | int l = t + 1; 33 | int r = n - 1; 34 | while(l < r){ 35 | int sum = num[l] + num[r] + num[i] + num[t]; 36 | if (sum == target){ 37 | ArrayList list = new ArrayList(); 38 | list.add(num[i]); 39 | list.add(num[t]); 40 | list.add(num[l]); 41 | list.add(num[r]); 42 | ret.add(new ArrayList<>(list)); 43 | l++;r--; 44 | while(l < r && num[l] == num[l-1]){ 45 | l++; 46 | } 47 | while(l < r && num[r] == num[r+1]){ 48 | r--; 49 | } 50 | }else if (sum < target){ 51 | l++; 52 | }else{ 53 | r--; 54 | } 55 | } 56 | } 57 | } 58 | return ret; 59 | } 60 | } -------------------------------------------------------------------------------- /LeetCode/Minimum Depth of Binary Tree/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 3 | public class Solution { 4 | public int run(TreeNode root) { 5 | return getMinDepth(root,false); 6 | } 7 | public int getMinDepth(TreeNode root,boolean hasBrother){ 8 | if (root == null){ 9 | if (hasBrother){ 10 | return Integer.MAX_VALUE; 11 | }else{ 12 | return 0; 13 | } 14 | } 15 | 16 | return Math.min(getMinDepth(root.left, root.right != null), 17 | getMinDepth(root.right, root.left != null)) + 1; 18 | } 19 | } -------------------------------------------------------------------------------- /LeetCode/README.md: -------------------------------------------------------------------------------- 1 | LeetCode solutions(Java) -------------------------------------------------------------------------------- /LeetCode/add-binary/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given two binary strings, return their sum (also a binary string). 4 | For example, 5 | a ="11" 6 | b ="1" 7 | Return"100". 8 | import java.util.*; 9 | public class Solution { 10 | public String addBinary(String a, String b) { 11 | int len1 = a.length(); 12 | int len2 = b.length(); 13 | int i = len1 - 1; 14 | int j = len2 - 1; 15 | int carry = 0; 16 | StringBuilder sb = new StringBuilder(); 17 | while(i>=0 || j>=0 || carry != 0){ 18 | int sum = carry; 19 | if (i>=0){ 20 | sum+=a.charAt(i) - '0'; 21 | i--; 22 | } 23 | if (j>=0){ 24 | sum+=b.charAt(j) - '0'; 25 | j--; 26 | } 27 | carry = sum / 2; 28 | sb.append( (char)(sum % 2 + '0')); 29 | } 30 | return sb.reverse().toString(); 31 | } 32 | } -------------------------------------------------------------------------------- /LeetCode/add-two-numbers/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Given a 2D board and a word, find if the word exists in the grid. 3 | The word can 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. 4 | For example, 5 | Given board = 6 | [ 7 | ["ABCE"], 8 | ["SFCS"], 9 | ["ADEE"] 10 | ] 11 | word ="ABCCED", -> returnstrue, 12 | word ="SEE", -> returnstrue, 13 | word ="ABCB", -> returnsfalse. 14 | 15 | public class Solution { 16 | boolean flag = false; 17 | int d[][]= {{-1,0},{1,0},{0,1},{0,-1}}; 18 | public boolean exist(char[][] board, String word) { 19 | if (word == null || word.length() == 0){ 20 | return true; 21 | } 22 | if (board == null || board.length == 0){ 23 | return false; 24 | } 25 | int row = board.length; 26 | int col = board[0].length; 27 | int len = word.length(); 28 | char c[] = new char[len]; 29 | for(int i = 0;i=0 && a=0 && b anagrams(String[] strs) { 8 | ArrayList ret = new ArrayList(); 9 | if (strs == null || strs.length == 0){ 10 | return ret; 11 | } 12 | HashMap> mp = new HashMap>(); 13 | for(String s:strs){ 14 | String t = sortString(s); 15 | if (!mp.containsKey(t)){ 16 | mp.put(t,new ArrayList()); 17 | } 18 | mp.get(t).add(s); 19 | } 20 | for(String s :mp.keySet()){ 21 | if (mp.get(s).size() > 1){ 22 | ret.addAll(mp.get(s)); 23 | } 24 | } 25 | return ret; 26 | } 27 | 28 | public String sortString(String s){ 29 | char[] c = s.toCharArray(); 30 | Arrays.sort(c); 31 | return new String(c); 32 | } 33 | } -------------------------------------------------------------------------------- /LeetCode/balanced-binary-tree/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Given a binary tree, determine if it is height-balanced. 3 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 4 | 5 | public class Solution { 6 | public boolean isBalanced(TreeNode root) { 7 | if (root == null){ 8 | return true; 9 | } 10 | int l = getDepth(root.left); 11 | int r = getDepth(root.right); 12 | return Math.abs(l-r) <= 1 && isBalanced(root.left) && isBalanced(root.right); 13 | } 14 | 15 | public int getDepth(TreeNode root){ 16 | if (root == null){ 17 | return 0; 18 | } 19 | return Math.max(getDepth(root.left),getDepth(root.right)) + 1; 20 | } 21 | } -------------------------------------------------------------------------------- /LeetCode/best-time-to-buy-and-sell-stock-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Say you have an array for which the i th element is the price of a given stock on day i. 4 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 5 | public class Solution { 6 | public int maxProfit(int[] prices) { 7 | if (prices == null || prices.length == 0){ 8 | return 0; 9 | } 10 | int sum = 0; 11 | for(int i = 1;i 0){ 13 | sum+=prices[i] - prices[i-1]; 14 | } 15 | } 16 | return sum; 17 | } 18 | } -------------------------------------------------------------------------------- /LeetCode/best-time-to-buy-and-sell-stock-iii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Say you have an array for which the i th element is the price of a given stock on day i. 4 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 5 | public class Solution { 6 | public int maxProfit(int[] prices) { 7 | if (prices == null || prices.length == 0){ 8 | return 0; 9 | } 10 | int len = prices.length; 11 | int lmin = prices[0]; 12 | int rmax = prices[len - 1]; 13 | int f[] = new int[len]; 14 | int g[] = new int[len]; 15 | for(int i = 1;i=0;i--){ 20 | rmax = Math.max(rmax,prices[i]); 21 | g[i] = Math.max(g[i+1],rmax-prices[i]); 22 | } 23 | 24 | int ans =0; 25 | for(int i = 0;i list = new ArrayList(); 16 | public ArrayList inorderTraversal(TreeNode root) { 17 | inorder(root); 18 | return list; 19 | } 20 | 21 | public void inorder(TreeNode root){ 22 | if (root == null){ 23 | return; 24 | } 25 | inorder(root.left); 26 | list.add(root.val); 27 | inorder(root.right); 28 | } 29 | } -------------------------------------------------------------------------------- /LeetCode/binary-tree-level-order-traversal-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a binary tree, return the bottom-up level ordertraversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 4 | For example: 5 | Given binary tree{3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | 12 | return its bottom-up level order traversal as: 13 | [ 14 | [15,7] 15 | [9,20], 16 | [3], 17 | ] 18 | import java.util.*; 19 | public class Solution { 20 | public ArrayList> levelOrderBottom(TreeNode root) { 21 | ArrayList> ret = new ArrayList>(); 22 | if (root == null){ 23 | return ret; 24 | } 25 | ArrayList list = new ArrayList(); 26 | LinkedList queue = new LinkedList(); 27 | TreeNode now = root; 28 | TreeNode last = root; 29 | queue.add(root); 30 | while(!queue.isEmpty()){ 31 | TreeNode t = queue.poll(); 32 | if (t.left != null){ 33 | queue.add(t.left); 34 | now = t.left; 35 | } 36 | if (t.right != null){ 37 | queue.add(t.right); 38 | now = t.right; 39 | } 40 | list.add(t.val); 41 | if (t == last){ 42 | ret.add(0,new ArrayList<>(list) ); 43 | last = now; 44 | list.clear(); 45 | } 46 | } 47 | return ret; 48 | } 49 | } -------------------------------------------------------------------------------- /LeetCode/binary-tree-level-order-traversal/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 4 | For example: 5 | Given binary tree{3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | 12 | return its level order traversal as: 13 | [ 14 | [3], 15 | [9,20], 16 | [15,7] 17 | ] 18 | import java.util.*; 19 | public class Solution { 20 | public ArrayList> levelOrder(TreeNode root) { 21 | ArrayList> ret = new ArrayList>(); 22 | if (root == null){ 23 | return ret; 24 | } 25 | ArrayList list = new ArrayList(); 26 | LinkedList queue = new LinkedList<>(); 27 | queue.push(root); 28 | TreeNode last = root; 29 | TreeNode now = root; 30 | while(!queue.isEmpty()){ 31 | TreeNode t = queue.poll(); 32 | if (t.left != null){ 33 | queue.add(t.left); 34 | now = t.left; 35 | } 36 | if (t.right != null){ 37 | queue.add(t.right); 38 | now = t.right; 39 | } 40 | list.add(t.val); 41 | if (last == t){ 42 | ret.add(new ArrayList<>(list)); 43 | list.clear(); 44 | last = now; 45 | } 46 | } 47 | return ret; 48 | } 49 | } -------------------------------------------------------------------------------- /LeetCode/binary-tree-maximum-path-sum/Main.java: -------------------------------------------------------------------------------- 1 | Given a binary tree, find the maximum path sum. 2 | The path may start and end at any node in the tree. 3 | For example: 4 | Given the below binary tree, 5 | 1 6 | / \ 7 | 2 3 8 | 9 | Return6. 10 | public class Solution { 11 | int ans = Integer.MIN_VALUE; 12 | public int maxPathSum(TreeNode root) { 13 | if (root == null){ 14 | return 0; 15 | } 16 | dfs(root); 17 | return ans; 18 | } 19 | public int dfs(TreeNode root){ 20 | if (root == null){ 21 | return 0; 22 | } 23 | int l = dfs(root.left); 24 | int r = dfs(root.right); 25 | int sum = root.val; 26 | if (l>0){ 27 | sum+=l; 28 | } 29 | if (r>0){ 30 | sum+=r; 31 | } 32 | ans = Math.max(sum,ans); 33 | if (Math.max(l,r) > 0){ 34 | return Math.max(l,r) + root.val; 35 | } 36 | return root.val; 37 | } 38 | } -------------------------------------------------------------------------------- /LeetCode/binary-tree-postorder-traversal/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a binary tree, return the postorder traversal of its nodes' values. 4 | For example: 5 | Given binary tree{1,#,2,3}, 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | 12 | return[3,2,1]. 13 | import java.util.*; 14 | public class Solution { 15 | ArrayList list = new ArrayList(); 16 | public ArrayList postorderTraversal(TreeNode root) { 17 | if (root == null){ 18 | return list; 19 | } 20 | postorder(root); 21 | return list; 22 | } 23 | public void postorder(TreeNode root){ 24 | if (root == null){ 25 | return; 26 | } 27 | postorder(root.left); 28 | postorder(root.right); 29 | list.add(root.val); 30 | } 31 | } -------------------------------------------------------------------------------- /LeetCode/binary-tree-preorder-traversal/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a binary tree, return the preorder traversal of its nodes' values. 4 | import java.util.*; 5 | public class Solution { 6 | ArrayList list = new ArrayList(); 7 | public ArrayList preorderTraversal(TreeNode root) { 8 | preorder(root); 9 | return list; 10 | } 11 | public void preorder(TreeNode root){ 12 | if (root == null){ 13 | return; 14 | } 15 | list.add(root.val); 16 | preorder(root.left); 17 | preorder(root.right); 18 | } 19 | } -------------------------------------------------------------------------------- /LeetCode/binary-tree-zigzag-level-order-traversal/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a binary tree, return the zigzag level ordertraversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). 4 | For example: 5 | Given binary tree{3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | 12 | return its zigzag level order traversal as: 13 | [ 14 | [3], 15 | [20,9], 16 | [15,7] 17 | ] 18 | 19 | import java.util.*; 20 | public class Solution { 21 | public ArrayList> zigzagLevelOrder(TreeNode root) { 22 | ArrayList> ret = new ArrayList>(); 23 | if (root == null){ 24 | return ret; 25 | } 26 | 27 | int level = 1; 28 | Stack s1 = new Stack<>(); 29 | Stack s2 = new Stack<>(); 30 | s1.push(root); 31 | while(!s1.isEmpty() || !s2.isEmpty()){ 32 | ArrayList list = new ArrayList(); 33 | if ((level & 1) == 1){ 34 | while(!s1.isEmpty()){ 35 | TreeNode t = s1.pop(); 36 | list.add(t.val); 37 | if (t.left != null){ 38 | s2.push(t.left); 39 | } 40 | if (t.right != null){ 41 | s2.push(t.right); 42 | } 43 | } 44 | }else{ 45 | while(!s2.isEmpty()){ 46 | TreeNode t = s2.pop(); 47 | list.add(t.val); 48 | if (t.right != null){ 49 | s1.push(t.right); 50 | } 51 | if (t.left != null){ 52 | s1.push(t.left); 53 | } 54 | 55 | } 56 | } 57 | level++; 58 | ret.add(new ArrayList<>(list)); 59 | } 60 | return ret; 61 | } 62 | } -------------------------------------------------------------------------------- /LeetCode/candy/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | There are N children standing in a line. Each child is assigned a rating value. 4 | You are giving candies to these children subjected to the following requirements: 5 | Each child must have at least one candy. 6 | Children with a higher rating get more candies than their neighbors. 7 | What is the minimum candies you must give? 8 | 9 | public class Solution { 10 | public int candy(int[] ratings) { 11 | if (ratings == null || ratings.length == 0){ 12 | return 0; 13 | } 14 | if (ratings.length == 1){ 15 | return 1; 16 | } 17 | int len = ratings.length; 18 | int inc = 1; 19 | int a[] = new int[len]; 20 | for (int i = 1;i ratings[i-1]){ 22 | a[i] = Math.max(a[i],inc++); 23 | }else{ 24 | inc = 1; 25 | } 26 | } 27 | inc = 1; 28 | for (int i = len - 2;i>=0;i--){ 29 | if (ratings[i] > ratings[i+1]){ 30 | a[i] = Math.max(a[i],inc++); 31 | }else{ 32 | inc = 1; 33 | } 34 | } 35 | int ans = 0; 36 | for (int i = 0;i map = new HashMap<>(); 8 | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { 9 | return dfs(node); 10 | } 11 | 12 | public UndirectedGraphNode dfs(UndirectedGraphNode node){ 13 | if (node == null){ 14 | return null; 15 | } 16 | if (map.containsKey(node.label)){ 17 | return map.get(node.label); 18 | } 19 | UndirectedGraphNode t = new UndirectedGraphNode(node.label); 20 | map.put(node.label,t); 21 | for(UndirectedGraphNode p : node.neighbors ){ 22 | t.neighbors.add(dfs(p)); 23 | } 24 | return t; 25 | } 26 | } -------------------------------------------------------------------------------- /LeetCode/combination-sum-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a collection of candidate numbers ( C ) and a target number ( T ), find all unique combinations in C where the candidate numbers sums to T . 4 | Each number in C may only be used once in the combination. 5 | Note: 6 | All numbers (including target) will be positive integers. 7 | Elements in a combination (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k). 8 | The solution set must not contain duplicate combinations. 9 | 10 | For example, given candidate set10,1,2,7,6,1,5and target8,  11 | A solution set is:  12 | [1, 7] 13 | [1, 2, 5] 14 | [2, 6] 15 | [1, 1, 6] 16 | import java.util.*; 17 | public class Solution { 18 | ArrayList> ret = new ArrayList>(); 19 | HashSet> set = new HashSet<>(); 20 | public ArrayList> combinationSum2(int[] num, int target) { 21 | if (num == null || num.length == 0){ 22 | return ret; 23 | } 24 | Arrays.sort(num); 25 | ArrayList list = new ArrayList(); 26 | HashMap map = new HashMap<>(); 27 | dfs(0,num,target,list,map); 28 | return ret; 29 | } 30 | 31 | public void dfs(int t,int[] num,int target,ArrayList list,HashMap map){ 32 | if (target == 0){ 33 | ret.add(new ArrayList<>(list)); 34 | return; 35 | } 36 | if (target < 0){ 37 | return; 38 | } 39 | for(int i = t;it && num[i] == num[i-1]){ 41 | continue; 42 | } 43 | list.add(num[i]); 44 | dfs(i+1,num,target - num[i],list,map); 45 | list.remove(list.size()-1); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /LeetCode/combination-sum/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Given a set of candidate numbers ( C ) and a target number ( T ), find all unique combinations in C where the candidate numbers sums to T . 3 | The same repeated number may be chosen from C unlimited number of times. 4 | Note: 5 | All numbers (including target) will be positive integers. 6 | Elements in a combination (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k). 7 | The solution set must not contain duplicate combinations. 8 | 9 | For example, given candidate set2,3,6,7and target7,  10 | A solution set is:  11 | [7] 12 | [2, 2, 3] 13 | 14 | import java.util.*; 15 | public class Solution { 16 | ArrayList> ret = new ArrayList>(); 17 | HashSet> set = new HashSet<>(); 18 | public ArrayList> combinationSum(int[] candidates, int target) { 19 | if (candidates == null || candidates.length == 0){ 20 | return ret; 21 | } 22 | Arrays.sort(candidates); 23 | ArrayList list = new ArrayList(); 24 | dfs(0,candidates,target,list); 25 | return ret; 26 | } 27 | 28 | public void dfs(int t, int[] candidates, int target, ArrayList list){ 29 | if (target == 0){ 30 | ret.add(new ArrayList(list)); 31 | return; 32 | } 33 | if (target < 0){ 34 | return; 35 | } 36 | for(int i = t;i> combine(int n, int k) { 18 | ArrayList> ret = new ArrayList>(); 19 | if (n == 0 || k>n){ 20 | return ret; 21 | } 22 | for(int i = 0;i<(1<= (1< list = new ArrayList(); 33 | for(int j = 0;j>(){ 43 | @Override 44 | public int compare(ArrayList o1, ArrayList o2){ 45 | for(int i = 0;i r){ 14 | return null; 15 | } 16 | if (l == r){ 17 | TreeNode root = new TreeNode(num[l]); 18 | return root; 19 | } 20 | int mid = l + ((r -l) >> 1); 21 | if (((r - l + 1) & 1) == 0){ 22 | mid += 1; 23 | } 24 | TreeNode root = new TreeNode(num[mid]); 25 | root.left = convertToBST(num,l,mid - 1); 26 | root.right = convertToBST(num,mid + 1,r); 27 | return root; 28 | } 29 | } -------------------------------------------------------------------------------- /LeetCode/convert-sorted-list-to-binary-search-tree/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 4 | public class Solution { 5 | public TreeNode sortedListToBST(ListNode head) { 6 | if (head == null){ 7 | return null; 8 | } 9 | return convertToBST(head,null); 10 | } 11 | 12 | public TreeNode convertToBST(ListNode head, ListNode end){ 13 | if (head == end){ 14 | return null; 15 | } 16 | ListNode slow = head; 17 | ListNode fast = head; 18 | while(fast != end && fast.next != end){ 19 | fast = fast.next.next; 20 | slow = slow.next; 21 | } 22 | TreeNode root = new TreeNode(slow.val); 23 | root.left = convertToBST(head,slow); 24 | root.right = convertToBST(slow.next,end); 25 | return root; 26 | } 27 | } -------------------------------------------------------------------------------- /LeetCode/copy-list-with-random-pointer/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 4 | Return a deep copy of the list. 5 | /** 6 | * Definition for singly-linked list with a random pointer. 7 | * class RandomListNode { 8 | * int label; 9 | * RandomListNode next, random; 10 | * RandomListNode(int x) { this.label = x; } 11 | * }; 12 | */ 13 | public class Solution { 14 | public RandomListNode copyRandomList(RandomListNode head) { 15 | if (head == null){ 16 | return null; 17 | } 18 | RandomListNode p = new RandomListNode(-1); 19 | RandomListNode q = new RandomListNode(head.label); 20 | RandomListNode s = p; 21 | p.next = q; 22 | p = p.next; 23 | RandomListNode t = head; 24 | while(head != null){ 25 | if (head.random != null){ 26 | p.random = new RandomListNode(head.random.label); 27 | } 28 | if (head.next != null){ 29 | p.next = new RandomListNode(head.next.label); 30 | } 31 | p = p.next; 32 | head = head.next; 33 | } 34 | 35 | return s.next; 36 | } 37 | } -------------------------------------------------------------------------------- /LeetCode/count-and-say/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | The count-and-say sequence is the sequence of integers beginning as follows: 4 | 1, 11, 21, 1211, 111221, ... 5 | 1is read off as"one 1"or11. 6 | 11is read off as"two 1s"or21. 7 | 21is read off as"one 2, thenone 1"or1211. 8 | Given an integer n, generate the n th sequence. 9 | Note: The sequence of integers will be represented as a string. 10 | import java.util.*; 11 | public class Solution { 12 | public String countAndSay(int n) { 13 | if (n <= 0){ 14 | return ""; 15 | } 16 | String s = "1"; 17 | for(int i = 1;i 1 5 | 'B' -> 2 6 | ... 7 | 'Z' -> 26 8 | Given an encoded message containing digits, determine the total number of ways to decode it. 9 | For example, 10 | Given encoded message"12", it could be decoded as"AB"(1 2) or"L"(12). 11 | The number of ways decoding"12"is 2. 12 | 13 | public class Solution { 14 | public int numDecodings(String s) { 15 | if (s == null || s.length() == 0){ 16 | return 0; 17 | } 18 | int len = s.length(); 19 | int f[] = new int[len+1]; 20 | f[0] = 1; 21 | if (s.charAt(0) > '0'){ 22 | f[1] = 1; 23 | } 24 | 25 | for(int i = 2;i<=len;i++){ 26 | if (s.charAt(i-1)>'0'){ 27 | f[i]=f[i-1]; 28 | } 29 | if (s.charAt(i-2)>'0'){ 30 | int a = Integer.parseInt(s.substring(i-2,i)); 31 | if (a>=10 && a<=26){ 32 | f[i]+=f[i-2]; 33 | } 34 | } 35 | } 36 | return f[len]; 37 | } 38 | } -------------------------------------------------------------------------------- /LeetCode/distinct-subsequences/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a string S and a string T, count the number of distinct subsequences of T in S. 4 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie,"ACE"is a subsequence of"ABCDE"while"AEC"is not). 5 | Here is an example: 6 | S ="rabbbit", T ="rabbit" 7 | Return3. 8 | public class Solution { 9 | public int numDistinct(String S, String T) { 10 | int len1 = S.length(); 11 | int len2 = T.length(); 12 | int f[][]= new int[len1 + 1][len2+ 1]; 13 | for(int i =0;i<=len1;i++){ 14 | f[i][0] = 1; 15 | } 16 | 17 | for(int i = 1;i<=len1;i++){ 18 | for(int j=1;j<=len2;j++){ 19 | if (S.charAt(i-1) == T.charAt(j-1)){ 20 | f[i][j] = f[i-1][j-1] + f[i-1][j]; 21 | }else{ 22 | f[i][j] = f[i-1][j]; 23 | } 24 | } 25 | } 26 | return f[len1][len2]; 27 | } 28 | } -------------------------------------------------------------------------------- /LeetCode/divide-two-integers/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Divide two integers without using multiplication, division and mod operator. 4 | public class Solution { 5 | public int divide(int dividend, int divisor) { 6 | if (divisor == 0){ 7 | return Integer.MAX_VALUE; 8 | } 9 | int sign = -1; 10 | if (dividend >= 0 && divisor > 0){ 11 | sign = 1; 12 | } 13 | if (dividend <= 0 && divisor < 0){ 14 | sign = 1; 15 | } 16 | long ans = 0; 17 | long a = Math.abs((long)dividend); 18 | long b = Math.abs((long)divisor); 19 | long k = b; 20 | long count = 1; 21 | while(a>=b){ 22 | k = b; 23 | count = 1; 24 | while(k + k <= a){ 25 | k += k; 26 | count += count; 27 | } 28 | a-=k; 29 | ans+=count; 30 | } 31 | //ans = solve(a,b); 32 | if (sign == 1){ 33 | return (int)ans; 34 | } 35 | return (int)(-ans); 36 | } 37 | 38 | private long solve(long ldividend, long ldivisor) { 39 | if(ldividend ((2 + 1) * 3) -> 9 7 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 8 | import java.util.*; 9 | public class Solution { 10 | public int evalRPN(String[] tokens) { 11 | if (tokens == null || tokens.length == 0){ 12 | return 0; 13 | } 14 | Stack stack = new Stack(); 15 | int len = tokens.length; 16 | for(String s : tokens){ 17 | if (! "+".equals(s) && ! "-".equals(s) && ! "*".equals(s) && ! "/".equals(s)){ 18 | stack.push(Integer.parseInt(s)); 19 | }else{ 20 | Integer b = stack.pop(); 21 | Integer a = stack.pop(); 22 | Integer c = 0; 23 | switch(s){ 24 | case "+" : c = a + b; 25 | break; 26 | case "-" : c = a - b; 27 | break; 28 | case "*" : c = a * b; 29 | break; 30 | default : c = a / b; 31 | break; 32 | } 33 | stack.push(c); 34 | } 35 | } 36 | return stack.pop(); 37 | } 38 | } -------------------------------------------------------------------------------- /LeetCode/first-missing-positive/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an unsorted integer array, find the first missing positive integer. 4 | For example, 5 | Given[1,2,0]return3, 6 | and[3,4,-1,1]return2. 7 | Your algorithm should run in O(n) time and uses constant space. 8 | 9 | public class Solution { 10 | public int firstMissingPositive(int[] A) { 11 | int n = A.length; 12 | for(int i = 0;i 0 && A[i] <= n && A[A[i] - 1] != A[i]){ 14 | swap(A,i,A[i] - 1); 15 | } 16 | } 17 | for(int i = 0;i list = new ArrayList(); 9 | public ArrayList generateParenthesis(int n) { 10 | if (n <= 0){ 11 | return list; 12 | } 13 | StringBuilder s = new StringBuilder(); 14 | getParenthesis(0,0,n,s); 15 | return list; 16 | } 17 | 18 | public void getParenthesis(int l,int r,int n,StringBuilder s){ 19 | if (l == n && r == n){ 20 | list.add(s.toString()); 21 | return; 22 | } 23 | if (r > n){ 24 | return; 25 | } 26 | StringBuilder t = new StringBuilder(s); 27 | if (l >= n){ 28 | getParenthesis(l,r+1,n,s.append(")")); 29 | }else if (l == r){ 30 | getParenthesis(l+1,r,n,s.append("(")); 31 | }else if (r < l){ 32 | getParenthesis(l+1,r,n,s.append("(")); 33 | getParenthesis(l,r+1,n,t.append(")")); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /LeetCode/gray-code/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | The gray code is a binary numeral system where two successive values differ in only one bit. 4 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 5 | For example, given n = 2, return[0,1,3,2]. Its gray code sequence is: 6 | 00 - 0 7 | 01 - 1 8 | 11 - 3 9 | 10 - 2 10 | import java.util.*; 11 | public class Solution { 12 | public ArrayList grayCode(int n) { 13 | ArrayList list = new ArrayList(); 14 | for(int i = 0;i<(1<>1)); 16 | } 17 | return list; 18 | } 19 | } -------------------------------------------------------------------------------- /LeetCode/implement-strstr/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Implement strStr(). 4 | Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 5 | import java.util.*; 6 | public class Solution { 7 | public String strStr(String haystack, String needle) { 8 | if (needle.length() == 0){ 9 | return haystack; 10 | } 11 | if (haystack.length() == 0){ 12 | return null; 13 | } 14 | int nextval[] = getNextval(needle.toCharArray()); 15 | int i = 0; 16 | int j = 0; 17 | while(i < haystack.length() && j < needle.length()){ 18 | if (j < 0 || haystack.charAt(i) == needle.charAt(j)){ 19 | i++; 20 | j++; 21 | }else{ 22 | j = nextval[j]; 23 | } 24 | } 25 | if (j == needle.length()){ 26 | return haystack.substring(i - j); 27 | } 28 | return null; 29 | } 30 | 31 | public int[] getNextval(char[] c){ 32 | int n = c.length; 33 | int i = 0; 34 | int j = -1; 35 | int[] nextval = new int[n]; 36 | nextval[0] = -1; 37 | while(i < n-1){ 38 | if (j == -1 || c[i] == c[j]){ 39 | i++; 40 | j++; 41 | if (c[i] != c[j]){ 42 | nextval[i] = j; 43 | }else{ 44 | nextval[i] = nextval[j]; 45 | } 46 | }else{ 47 | j = nextval[j]; 48 | } 49 | } 50 | return nextval; 51 | } 52 | } -------------------------------------------------------------------------------- /LeetCode/insert-interval/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 4 | You may assume that the intervals were initially sorted according to their start times. 5 | Example 1:  6 | Given intervals[1,3],[6,9], insert and merge[2,5]in as[1,5],[6,9]. 7 | Example 2:  8 | Given[1,2],[3,5],[6,7],[8,10],[12,16], insert and merge[4,9]in as[1,2],[3,10],[12,16]. 9 | This is because the new interval[4,9]overlaps with[3,5],[6,7],[8,10]. 10 | import java.util.*; 11 | public class Solution { 12 | public ArrayList insert(ArrayList intervals, Interval newInterval) { 13 | ArrayList list = new ArrayList(); 14 | int index = 0; 15 | for(Interval a : intervals){ 16 | if (a.start > newInterval.end){ 17 | list.add(a); 18 | }else if (a.end < newInterval.start){ 19 | list.add(a); 20 | index++; 21 | }else{ 22 | newInterval.start = Math.min(a.start,newInterval.start); 23 | newInterval.end = Math.max(a.end,newInterval.end); 24 | } 25 | } 26 | list.add(index,newInterval); 27 | return list; 28 | } 29 | } -------------------------------------------------------------------------------- /LeetCode/insertion-sort-list/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Sort a linked list using insertion sort. 4 | 5 | public class Solution { 6 | public ListNode insertionSortList(ListNode head) { 7 | if (head == null){ 8 | return head; 9 | } 10 | ListNode h = new ListNode(-1); 11 | h.next = head; 12 | ListNode p = head; 13 | while(p!=null && p.next != null){ 14 | if (p.val <= p.next.val){ 15 | p = p.next; 16 | continue; 17 | } 18 | ListNode t = h; 19 | while(t.next != null && t.next.val <= p.next.val){ 20 | t = t.next; 21 | } 22 | ListNode q = p.next; 23 | p.next = p.next.next; 24 | q.next = t.next; 25 | t.next = q; 26 | } 27 | return h.next; 28 | } 29 | } -------------------------------------------------------------------------------- /LeetCode/integer-to-roman/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an integer, convert it to a roman numeral. 4 | Input is guaranteed to be within the range from 1 to 3999. 5 | import java.util.*; 6 | public class Solution { 7 | public String intToRoman(int num) { 8 | int[] a = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 9 | String[] b = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; 10 | StringBuilder sb = new StringBuilder(); 11 | for(int i = 0;i= a[i]){ 13 | num-=a[i]; 14 | sb.append(b[i]); 15 | } 16 | 17 | } 18 | return sb.toString(); 19 | } 20 | } -------------------------------------------------------------------------------- /LeetCode/interleaving-string/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 4 | For example, 5 | Given: 6 | s1 ="aabcc", 7 | s2 ="dbbca", 8 | When s3 ="aadbbcbcac", return true. 9 | When s3 ="aadbbbaccc", return false. 10 | public class Solution { 11 | public boolean isInterleave(String s1, String s2, String s3) { 12 | int len1 = s1.length(); 13 | int len2 = s2.length(); 14 | if (len1 + len2 != s3.length()){ 15 | return false; 16 | } 17 | boolean f[][] = new boolean[len1 + 1][len2 + 1]; 18 | f[0][0] = true; 19 | for(int i = 1;i<=len1;i++){ 20 | if (s3.charAt(i - 1) == s1.charAt(i - 1)){ 21 | f[i][0] = f[i-1][0]; 22 | } 23 | } 24 | for(int i = 1;i<=len2;i++){ 25 | if (s3.charAt(i - 1) == s2.charAt(i - 1)){ 26 | f[0][i] = f[0][i-1]; 27 | } 28 | } 29 | for(int i = 1 ;i<=len1;i++){ 30 | for(int j = 1;j<=len2;j++){ 31 | if (s3.charAt(i + j -1) == s1.charAt(i - 1)){ 32 | f[i][j] = f[i][j] || f[i-1][j]; 33 | } 34 | if (s3.charAt(i + j -1) == s2.charAt(j - 1)){ 35 | f[i][j] = f[i][j] || f[i][j-1]; 36 | } 37 | } 38 | } 39 | return f[len1][len2]; 40 | } 41 | } -------------------------------------------------------------------------------- /LeetCode/jump-game-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 4 | Each element in the array represents your maximum jump length at that position. 5 | Your goal is to reach the last index in the minimum number of jumps. 6 | For example: 7 | Given array A =[2,3,1,1,4] 8 | The minimum number of jumps to reach the last index is2. (Jump1step from index 0 to 1, then3steps to the last index.) 9 | public class Solution { 10 | public int jump(int[] A) { 11 | if (A == null || A.length == 0){ 12 | return 0; 13 | } 14 | int n = A.length; 15 | int f[] = new int[n]; 16 | for(int i = 0;i=i;i++){ 17 | max = Math.max(max,i+A[i]); 18 | } 19 | if (max >= len-1){ 20 | return true; 21 | } 22 | return false; 23 | } 24 | } -------------------------------------------------------------------------------- /LeetCode/largest-rectangle-in-histogram/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. 4 | 5 | Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3]. 6 | 7 | 8 | The largest rectangle is shown in the shaded area, which has area =10unit. 9 | 10 | For example, 11 | Given height =[2,1,5,6,2,3], 12 | return10. 13 | import java.util.*; 14 | public class Solution { 15 | public int largestRectangleArea(int[] height) { 16 | if (height == null || height.length == 0){ 17 | return 0; 18 | } 19 | int ans = 0; 20 | int n = height.length; 21 | Stack s = new Stack<>(); 22 | s.push(-1); 23 | for(int i = 0;i letterCombinations(String digits) { 11 | ArrayList list = new ArrayList(); 12 | if (digits == null){ 13 | return list; 14 | } 15 | String[] dic = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 16 | int n = digits.length(); 17 | list.add(""); 18 | for(int i = 0;i mp = new HashMap(); 12 | for(int t:num){ 13 | mp.put(t,false); 14 | } 15 | Iterator it = mp.keySet().iterator(); 16 | int ans = 0; 17 | while(it.hasNext()){ 18 | Integer t = it.next(); 19 | if (mp.get(t)){ 20 | continue; 21 | } 22 | mp.put(t,true); 23 | int count = 1; 24 | int s = t-1; 25 | while(mp.containsKey(s)){ 26 | count++; 27 | mp.put(s,true); 28 | s--; 29 | } 30 | int b = t+1; 31 | while(mp.containsKey(b)){ 32 | count++; 33 | mp.put(b,true); 34 | b++; 35 | } 36 | ans = Math.max(ans,count); 37 | 38 | } 39 | return ans; 40 | } 41 | } -------------------------------------------------------------------------------- /LeetCode/longest-palindromic-substring/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 4 | public class Solution { 5 | public String longestPalindrome(String s) { 6 | if (s == null || s.length() <= 1){ 7 | return s; 8 | } 9 | int n = s.length(); 10 | boolean f[][] = new boolean[n+1][n+1]; 11 | String t = ""; 12 | int max = 0; 13 | 14 | for(int i = n;i>=1;i--){ 15 | f[i][i] = true; 16 | for(int j = i+1;j<=n;j++){ 17 | f[i][j] = (s.charAt(i-1) == s.charAt(j-1) && (j - i < 2 || f[i+1][j-1])); 18 | if (f[i][j] && j-i+1 > max){ 19 | max = j-i+1; 20 | t = s.substring(i-1,j); 21 | } 22 | } 23 | } 24 | return t; 25 | } 26 | } -------------------------------------------------------------------------------- /LeetCode/longest-substring-without-repeating-characters/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. 4 | import java.util.*; 5 | public class Solution { 6 | public int lengthOfLongestSubstring(String s) { 7 | if (s == null || s.length() == 0){ 8 | return 0; 9 | } 10 | HashMap map = new HashMap<>(); 11 | char[] c = s.toCharArray(); 12 | int ans = 0; 13 | int left = 0; 14 | for(int i = 0;i stack = new Stack<>(); 15 | int ans = 0; 16 | for(int i = 0;i mp = new HashMap<>(); 17 | for(Point b:points){ 18 | if (a.equals(b)){ 19 | continue; 20 | } 21 | int x2 = b.x; 22 | int y2 = b.y; 23 | if (x2 == x1){ 24 | if (y1 == y2){ 25 | same++; 26 | }else{ 27 | m++; 28 | } 29 | continue; 30 | } 31 | double scope = getScope(x1,y1,x2,y2); 32 | if (!mp.containsKey(scope)){ 33 | mp.put(scope,1); 34 | }else{ 35 | int k = mp.get(scope); 36 | mp.put(scope,k+1); 37 | } 38 | 39 | } 40 | int ma = m; 41 | for(HashMap.Entry e : mp.entrySet()){ 42 | ma = Math.max(ma,e.getValue()); 43 | } 44 | ans = Math.max(ans,ma + same); 45 | } 46 | 47 | return ans; 48 | 49 | } 50 | public double getScope(int x1,int y1,int x2,int y2){ 51 | return (y1-y2)*1.0/(x1-x2); 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /LeetCode/maximal-rectangle/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. 4 | import java.util.*; 5 | public class Solution { 6 | public int maximalRectangle(char[][] matrix) { 7 | if (matrix == null || matrix.length == 0){ 8 | return 0; 9 | } 10 | int row = matrix.length; 11 | int col = matrix[0].length; 12 | int ans = 0; 13 | int height[] = new int[col + 1]; 14 | for(int k = 0;k s = new Stack<>(); 23 | s.push(-1); 24 | for(int i = 0;i>1) + 1)*1.0; 12 | }else{ 13 | return (findKth(A,n,B,m,(t>>1)) + findKth(A,n,B,m,(t>>1) + 1) ) / 2.0; 14 | } 15 | } 16 | 17 | public int findKth(int[] A,int n,int[] B, int m,int k){ 18 | if (n>m){ 19 | return findKth(B,m,A,n,k); 20 | } 21 | if (n == 0){ 22 | return B[k-1]; 23 | } 24 | if (k == 1){ 25 | return Math.min(A[0],B[0]); 26 | } 27 | int l1 = Math.min(n,k>>1); 28 | int l2 = k - l1; 29 | if (A[l1-1] < B[l2-1]){ 30 | return findKth(Arrays.copyOfRange(A,l1,A.length),n-l1,B,m,k-l1); 31 | }else if (A[l1-1] > B[l2-1]){ 32 | return findKth(A,n,Arrays.copyOfRange(B,l2,B.length),m-l2,k-l2); 33 | }else{ 34 | return A[l1-1]; 35 | } 36 | 37 | } 38 | } -------------------------------------------------------------------------------- /LeetCode/merge-intervals/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a collection of intervals, merge all overlapping intervals. 4 | For example, 5 | Given[1,3],[2,6],[8,10],[15,18], 6 | return[1,6],[8,10],[15,18]. 7 | import java.util.*; 8 | public class Solution { 9 | public ArrayList merge(ArrayList intervals) { 10 | ArrayList list = new ArrayList(); 11 | if (intervals.size() <= 1){ 12 | return intervals; 13 | } 14 | Collections.sort(intervals,new Comparator(){ 15 | @Override 16 | public int compare(Interval o1, Interval o2){ 17 | return o1.start - o2.start; 18 | } 19 | }); 20 | for(int i = 1;i lists) { 7 | if (lists == null || lists.size() == 0){ 8 | return null; 9 | } 10 | if (lists.size() == 1){ 11 | return lists.get(0); 12 | } 13 | PriorityQueue queue = new PriorityQueue(lists.size(),new Comparator(){ 14 | @Override 15 | public int compare(ListNode o1, ListNode o2){ 16 | if (o1.val > o2.val){ 17 | return 1; 18 | }else if (o1.val < o2.val){ 19 | return -1; 20 | } 21 | return 0; 22 | } 23 | }); 24 | int n = lists.size(); 25 | for(int i = 0;i=0 && j>=0){ 10 | if (A[i] > B[j]){ 11 | A[index--] = A[i--]; 12 | }else{ 13 | A[index--] = B[j--]; 14 | } 15 | } 16 | while(j>=0){ 17 | A[index--] = B[j--]; 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /LeetCode/merge-two-sorted-lists/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 4 | public class Solution { 5 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 6 | if (l1 == null && l2 == null){ 7 | return null; 8 | } 9 | if (l1 != null && l2 == null){ 10 | return l1; 11 | } 12 | if (l1 == null && l2 != null){ 13 | return l2; 14 | } 15 | ListNode p = new ListNode(-1); 16 | ListNode t = p; 17 | while(l1!=null && l2 != null){ 18 | if (l1.val < l2.val){ 19 | p.next = l1; 20 | l1 = l1.next; 21 | }else{ 22 | p.next = l2; 23 | l2 = l2.next; 24 | } 25 | p = p.next; 26 | } 27 | if (l1 != null){ 28 | p.next = l1; 29 | } 30 | if (l2 != null){ 31 | p.next = l2; 32 | } 33 | return t.next; 34 | } 35 | } -------------------------------------------------------------------------------- /LeetCode/minimum-path-sum/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 4 | public class Solution { 5 | public int minPathSum(int[][] grid) { 6 | if (grid == null || grid.length == 0){ 7 | return 0; 8 | } 9 | int row = grid.length; 10 | int col = grid[0].length; 11 | int f[][] = new int[row+1][col+1]; 12 | f[0][0] = grid[0][0]; 13 | for(int i = 1;i n || m == 0){ 20 | return ""; 21 | } 22 | HashMap map = new HashMap<>(); 23 | int c[] = new int[256]; 24 | boolean dic[] = new boolean[256]; 25 | for(int i = 0;i 0){ 35 | c[S.charAt(i)]--; 36 | count++; 37 | }else{ 38 | c[S.charAt(i)]--; 39 | } 40 | while(count == m){ 41 | char ch = S.charAt(left); 42 | if (i - left + 1 < ans){ 43 | ans = i - left + 1; 44 | l = left; 45 | } 46 | if (dic[ch]){ 47 | c[ch]++; 48 | if (c[ch] > 0){ 49 | count--; 50 | } 51 | } 52 | left++; 53 | } 54 | } 55 | if (ans == Integer.MAX_VALUE){ 56 | return ""; 57 | } 58 | return S.substring(l,l + ans); 59 | } 60 | } -------------------------------------------------------------------------------- /LeetCode/multiply-strings/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given two numbers represented as strings, return multiplication of the numbers as a string. 4 | Note: The numbers can be arbitrarily large and are non-negative. 5 | import java.math.*; 6 | public class Solution { 7 | public String multiply(String num1, String num2) { 8 | BigDecimal a = new BigDecimal(num1); 9 | BigDecimal b = new BigDecimal(num2); 10 | return a.multiply(b).toString(); 11 | } 12 | } -------------------------------------------------------------------------------- /LeetCode/n-queens-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Follow up for N-Queens problem. 4 | Now, instead outputting board configurations, return the total number of distinct solutions. 5 | 6 | import java.util.*; 7 | public class Solution { 8 | ArrayList list = new ArrayList(); 9 | public int totalNQueens(int n) { 10 | if (n<=0){ 11 | return 1; 12 | } 13 | char[][] mp = new char[n][n]; 14 | for(int i = 0;i list = new ArrayList(); 23 | public ArrayList solveNQueens(int n) { 24 | if (n<=0){ 25 | return list; 26 | } 27 | char[][] mp = new char[n][n]; 28 | for(int i = 0;i=0 && num[i+1]<=num[i]){ 19 | i--; 20 | } 21 | if (i>=0){ 22 | int j = i+1; 23 | while(jnum[i]){ 24 | j++; 25 | } 26 | j--; 27 | swap(num,i,j); 28 | reverse(num,i+1,len-1); 29 | }else{ 30 | Arrays.sort(num); 31 | } 32 | } 33 | 34 | public void swap(int[] num,int i,int j){ 35 | int t =num[i]; 36 | num[i] = num[j]; 37 | num[j] = t; 38 | } 39 | 40 | public void reverse(int[] num,int l, int r){ 41 | for(int i = l;i<=(l+r)/2;i++){ 42 | swap(num,i,r-(i-l)); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /LeetCode/palindrome-number/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Determine whether an integer is a palindrome. Do this without extra space. 4 | click to show spoilers. 5 | public class Solution { 6 | public boolean isPalindrome(int x) { 7 | if (x < 0){ 8 | return false; 9 | } 10 | long a = x; 11 | long b = 0; 12 | while(a > 0){ 13 | b = b*10 + a % 10; 14 | a/=10; 15 | } 16 | return x == b; 17 | } 18 | } -------------------------------------------------------------------------------- /LeetCode/palindrome-partitioning-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a string s, partition s such that every substring of the partition is a palindrome. 4 | Return the minimum cuts needed for a palindrome partitioning of s. 5 | For example, given s ="aab", 6 | Return1since the palindrome partitioning["aa","b"]could be produced using 1 cut. 7 | public class Solution { 8 | public int minCut(String s) { 9 | if (s == null || s.length() == 0){ 10 | return 0; 11 | } 12 | int len = s.length(); 13 | boolean p[][] = new boolean[len][len]; 14 | int f[] = new int[len + 2]; 15 | f[len] = -1; 16 | for(int i = len - 1;i>=0;i--){ 17 | f[i] = Integer.MAX_VALUE; 18 | for(int j = i;j<=len - 1;j++){ 19 | if (s.charAt(i) == s.charAt(j) && (j - i <= 1 || p[i+1][j-1])){ 20 | p[i][j] = true; 21 | f[i] = Math.min(f[i],f[j+1] + 1); 22 | } 23 | } 24 | } 25 | return f[0]; 26 | } 27 | } -------------------------------------------------------------------------------- /LeetCode/palindrome-partitioning/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a string s, partition s such that every substring of the partition is a palindrome. 4 | Return all possible palindrome partitioning of s. 5 | For example, given s ="aab", 6 | Return 7 | [ 8 | ["aa","b"], 9 | ["a","a","b"] 10 | ] 11 | import java.util.*; 12 | public class Solution { 13 | ArrayList> ret = new ArrayList>(); 14 | ArrayList list = new ArrayList(); 15 | public ArrayList> partition(String s) { 16 | if (s == null || s.length()==0){ 17 | return ret; 18 | } 19 | dfs(s,0); 20 | return ret; 21 | } 22 | public void dfs(String s,int l){ 23 | if (list.size() > 0 && l>=s.length()){ 24 | ret.add(new ArrayList<>(list)); 25 | return; 26 | } 27 | if (l>=s.length()){ 28 | return; 29 | } 30 | for(int i = l;i4->3->2->5->2and x = 3, 7 | return1->2->2->4->3->5. 8 | public class Solution { 9 | public ListNode partition(ListNode head, int x) { 10 | if (head == null){ 11 | return null; 12 | } 13 | ListNode l1 = new ListNode(-1); 14 | ListNode l2 = new ListNode(-1); 15 | ListNode p = l1; 16 | ListNode t = l2; 17 | while(head != null){ 18 | if (head.val < x){ 19 | p.next = head; 20 | p = head; 21 | }else{ 22 | t.next = head; 23 | t = head; 24 | } 25 | head = head.next; 26 | } 27 | p.next = l2.next; 28 | t.next = null; 29 | return l1.next; 30 | } 31 | } -------------------------------------------------------------------------------- /LeetCode/pascals-triangle-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an index k, return the k th row of the Pascal's triangle. 4 | For example, given k = 3, 5 | Return[1,3,3,1]. 6 | 7 | import java.util.*; 8 | public class Solution { 9 | public ArrayList getRow(int rowIndex) { 10 | ArrayList list = new ArrayList(); 11 | 12 | int f[] = new int[rowIndex+1]; 13 | f[0] = 1; 14 | for(int i =1;i<=rowIndex;i++){ 15 | for(int j = i;j>=1;j--){ 16 | f[j]+=f[j-1]; 17 | } 18 | } 19 | for(int i =0;i<=rowIndex;i++){ 20 | list.add(f[i]); 21 | } 22 | return list; 23 | } 24 | } -------------------------------------------------------------------------------- /LeetCode/pascals-triangle/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given numRows, generate the first numRows of Pascal's triangle. 4 | For example, given numRows = 5, 5 | Return 6 | [ 7 | [1], 8 | [1,1], 9 | [1,2,1], 10 | [1,3,3,1], 11 | [1,4,6,4,1] 12 | ] 13 | import java.util.*; 14 | public class Solution { 15 | public ArrayList> generate(int numRows) { 16 | ArrayList> ret = new ArrayList>(); 17 | if (numRows == 0){ 18 | return ret; 19 | } 20 | for(int i=0;i list = new ArrayList(); 22 | for(int j=1;j<=i+1;j++){ 23 | if (j==1 || j==i+1){ 24 | list.add(1); 25 | continue; 26 | } 27 | int a = ret.get(i-1).get(j-2); 28 | int b = ret.get(i-1).get(j-1); 29 | list.add(a+b); 30 | } 31 | ret.add(new ArrayList<>(list)); 32 | } 33 | return ret; 34 | } 35 | } -------------------------------------------------------------------------------- /LeetCode/path-sum-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 4 | For example: 5 | Given the below binary tree andsum = 22, 6 | 5 7 | / \ 8 | 4 8 9 | / / \ 10 | 11 13 4 11 | / \ / \ 12 | 7 2 5 1 13 | return 14 | [ 15 | [5,4,11,2], 16 | [5,8,4,5] 17 | ] 18 | 19 | import java.util.*; 20 | public class Solution { 21 | ArrayList> ret = new ArrayList>(); 22 | ArrayList list = new ArrayList(); 23 | public ArrayList> pathSum(TreeNode root, int sum) { 24 | if (root == null){ 25 | return ret; 26 | } 27 | list.add(root.val); 28 | dfs(root,sum-root.val); 29 | return ret; 30 | } 31 | public void dfs(TreeNode root,int sum){ 32 | if (root == null){ 33 | return; 34 | } 35 | if (sum == 0 && root.left == null && root.right == null){ 36 | ret.add(new ArrayList<>(list)); 37 | return; 38 | } 39 | 40 | if (root.left != null){ 41 | list.add(root.left.val); 42 | dfs(root.left, sum-root.left.val); 43 | list.remove(list.size()-1); 44 | } 45 | if (root.right != null){ 46 | list.add(root.right.val); 47 | dfs(root.right, sum-root.right.val); 48 | list.remove(list.size()-1); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /LeetCode/path-sum/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 3 | For example: 4 | Given the below binary tree andsum = 22, 5 | 5 6 | / \ 7 | 4 8 8 | / / \ 9 | 11 13 4 10 | / \ \ 11 | 7 2 1 12 | return true, as there exist a root-to-leaf path5->4->11->2which sum is 22. 13 | 14 | public class Solution { 15 | public boolean hasPathSum(TreeNode root, int sum) { 16 | if (root == null){ 17 | return false; 18 | } 19 | return dfs(root,sum - root.val); 20 | } 21 | 22 | public boolean dfs(TreeNode root,int sum){ 23 | if (sum == 0 && root.left == null && root.right == null){ 24 | return true; 25 | } 26 | boolean l = false; 27 | boolean r = false; 28 | if (root.left != null){ 29 | l = dfs(root.left,sum-root.left.val); 30 | } 31 | if (root.right != null){ 32 | r = dfs(root.right,sum-root.right.val); 33 | } 34 | return l || r; 35 | } 36 | } -------------------------------------------------------------------------------- /LeetCode/permutation-sequence/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | The set[1,2,3,…,n]contains a total of n! unique permutations. 4 | By listing and labeling all of the permutations in order, 5 | We get the following sequence (ie, for n = 3): 6 | ."123" 7 | ."132" 8 | ."213" 9 | ."231" 10 | ."312" 11 | ."321" 12 | 13 | Given n and k, return the k th permutation sequence. 14 | Note: Given n will be between 1 and 9 inclusive. 15 | import java.util.*; 16 | public class Solution { 17 | public String getPermutation(int n, int k) { 18 | int a[] = new int[n+1]; 19 | for(int i = 1;i<=n;i++){ 20 | a[i] = i; 21 | } 22 | for(int i = 1;i<=k-1;i++){ 23 | nextPermutation(a); 24 | } 25 | StringBuilder sb = new StringBuilder(); 26 | for(int i = 1;i<=n;i++){ 27 | sb.append((char)(a[i]+'0')); 28 | } 29 | return sb.toString(); 30 | } 31 | public void nextPermutation(int[] a){ 32 | int len = a.length; 33 | int i = len - 2; 34 | while(i>=0 && a[i+1]=0){ 38 | int j = i+1; 39 | while(j < len && a[j]>a[i]){ 40 | j++; 41 | } 42 | j--; 43 | swap(a,i,j); 44 | } 45 | reverse(a,i+1,len-1); 46 | } 47 | 48 | public void swap(int[] a ,int i,int j){ 49 | int t = a[i]; 50 | a[i] = a[j]; 51 | a[j] = t; 52 | } 53 | public void reverse(int[] a ,int l,int r){ 54 | for(int i = l;i<=(l+r)/2;i++){ 55 | swap(a,i,r-(i-l)); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /LeetCode/permutations-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 4 | For example, 5 | [1,1,2]have the following unique permutations: 6 | [1,1,2],[1,2,1], and[2,1,1]. 7 | import java.util.*; 8 | public class Solution { 9 | ArrayList> ret = new ArrayList>(); 10 | HashSet> set = new HashSet>(); 11 | public ArrayList> permuteUnique(int[] num) { 12 | if (num == null || num.length == 0){ 13 | return ret; 14 | } 15 | Arrays.sort(num); 16 | int n = num.length; 17 | dfs(0,n,num); 18 | Iterator> it = set.iterator(); 19 | while(it.hasNext()){ 20 | ret.add(it.next()); 21 | } 22 | return ret; 23 | } 24 | public void dfs(int t, int n, int[] num){ 25 | if (t >= n){ 26 | return; 27 | } 28 | ArrayList list = new ArrayList(); 29 | for(int i = 0;i> ret = new ArrayList>(); 10 | HashSet> set = new HashSet>(); 11 | public ArrayList> permute(int[] num) { 12 | if (num == null || num.length == 0){ 13 | return ret; 14 | } 15 | Arrays.sort(num); 16 | int n = num.length; 17 | dfs(0,n,num); 18 | Iterator> it = set.iterator(); 19 | while(it.hasNext()){ 20 | ret.add(it.next()); 21 | } 22 | return ret; 23 | } 24 | public void dfs(int t, int n, int[] num){ 25 | if (t >= n){ 26 | return; 27 | } 28 | ArrayList list = new ArrayList(); 29 | for(int i = 0;i=0;i--){ 12 | a[index++] = (carry + digits[i]) % 10; 13 | carry = (carry + digits[i]) / 10; 14 | } 15 | if (carry > 0){ 16 | a[index++] = carry; 17 | } 18 | int ans[] = new int[index]; 19 | for(int i = index - 1;i>=0;i--){ 20 | ans[index - 1 - i] = a[i]; 21 | } 22 | return ans; 23 | } 24 | } -------------------------------------------------------------------------------- /LeetCode/populating-next-right-pointers-in-each-node-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Follow up for problem "Populating Next Right Pointers in Each Node". 4 | What if the given tree could be any binary tree? Would your previous solution still work? 5 | Note: 6 | You may only use constant extra space. 7 | 8 | For example, 9 | Given the following binary tree, 10 | 1 11 | / \ 12 | 2 3 13 | / \ \ 14 | 4 5 7 15 | 16 | After calling your function, the tree should look like: 17 | 1 -> NULL 18 | / \ 19 | 2 -> 3 -> NULL 20 | / \ \ 21 | 4-> 5 -> 7 -> NULL 22 | import java.util.*; 23 | public class Solution { 24 | public void connect(TreeLinkNode root) { 25 | if (root == null){ 26 | return; 27 | } 28 | LinkedList queue = new LinkedList<>(); 29 | queue.add(root); 30 | while(!queue.isEmpty()){ 31 | int n = queue.size(); 32 | for(int i = 0;i queue = new LinkedList<>(); 19 | queue.add(root); 20 | while(!queue.isEmpty()){ 21 | int n = queue.size(); 22 | //TreeLinkNode t = queue.poll(); 23 | for(int i = 0;i<=n-1;i++){ 24 | TreeLinkNode t = queue.poll(); 25 | if (t.left != null){ 26 | queue.add(t.left); 27 | } 28 | if (t.right != null){ 29 | queue.add(t.right); 30 | } 31 | if (n > 1){ 32 | t.next = queue.peek(); 33 | } 34 | if (i == n-1){ 35 | t.next = null; 36 | } 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /LeetCode/powx-n/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Implement pow(x, n). 4 | public class Solution { 5 | public double pow(double x, int n) { 6 | int sign = 1; 7 | if (n < 0){ 8 | sign = 0; 9 | n = -n; 10 | } 11 | double ans = 1.0; 12 | double b = x; 13 | while(n>0){ 14 | if ((n & 1) == 1){ 15 | ans *= b; 16 | } 17 | b = b*b; 18 | n>>=1; 19 | } 20 | if (sign == 0){ 21 | return 1.0/ans; 22 | } 23 | return ans; 24 | } 25 | } -------------------------------------------------------------------------------- /LeetCode/recover-binary-search-tree/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Two elements of a binary search tree (BST) are swapped by mistake. 4 | Recover the tree without changing its structure. 5 | import java.util.*; 6 | public class Solution { 7 | ArrayList list = new ArrayList<>(); 8 | public void recoverTree(TreeNode root) { 9 | inOrderTraverse(root); 10 | TreeNode a = root; 11 | TreeNode b = root; 12 | for(int i = 1;i=1;i--){ 19 | if (list.get(i).val < list.get(i-1).val){ 20 | b = list.get(i); 21 | break; 22 | } 23 | } 24 | int t = a.val; 25 | a.val = b.val; 26 | b.val = t; 27 | } 28 | 29 | public void inOrderTraverse(TreeNode root){ 30 | if (root == null){ 31 | return; 32 | } 33 | inOrderTraverse(root.left); 34 | list.add(root); 35 | inOrderTraverse(root.right); 36 | } 37 | } -------------------------------------------------------------------------------- /LeetCode/regular-expression-matching/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Implement regular expression matching with support for'.'and'*'. 4 | '.' Matches any single character. 5 | '*' Matches zero or more of the preceding element. 6 | 7 | The matching should cover the entire input string (not partial). 8 | 9 | The function prototype should be: 10 | bool isMatch(const char *s, const char *p) 11 | 12 | Some examples: 13 | isMatch("aa","a") → false 14 | isMatch("aa","aa") → true 15 | isMatch("aaa","aa") → false 16 | isMatch("aa", "a*") → true 17 | isMatch("aa", ".*") → true 18 | isMatch("ab", ".*") → true 19 | isMatch("aab", "c*a*b") → true 20 | 21 | public class Solution { 22 | public boolean isMatch(String s, String p) { 23 | if (s == null && p == null){ 24 | return true; 25 | } 26 | int n = s.length(); 27 | int m = p.length(); 28 | if (n == 0 && m == 0){ 29 | return true; 30 | } 31 | 32 | boolean f[][] = new boolean[n+1][m+1]; 33 | f[0][0] = true; 34 | if (m>=1){ 35 | if (p.charAt(0) == '*'){ 36 | f[0][1] = true; 37 | }else{ 38 | f[0][1] = false; 39 | } 40 | } 41 | for(int i = 1;i=2 && s.charAt(i-1) != p.charAt(j-2) && p.charAt(j-2) != '.'){ 53 | f[i][j] = f[i][j-2]; 54 | }else{ 55 | f[i][j] = f[i][j-1] || f[i][j-2] || f[i-1][j]; 56 | } 57 | } 58 | } 59 | } 60 | 61 | return f[n][m]; 62 | 63 | } 64 | } -------------------------------------------------------------------------------- /LeetCode/remove-duplicates-from-sorted-array-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Follow up for "Remove Duplicates": 4 | What if duplicates are allowed at most twice? 5 | For example, 6 | Given sorted array A =[1,1,1,2,2,3], 7 | Your function should return length =5, and A is now[1,1,2,2,3]. 8 | 9 | public class Solution { 10 | public int removeDuplicates(int[] A) { 11 | if (A == null || A.length == 0){ 12 | return 0; 13 | } 14 | int n = A.length; 15 | if (n <= 2){ 16 | return n; 17 | } 18 | int index = 2; 19 | for(int i = 2;i2->3->3->4->4->5, return1->2->5. 6 | Given1->1->1->2->3, return2->3. 7 | public class Solution { 8 | public ListNode deleteDuplicates(ListNode head) { 9 | if (head == null || head.next == null){ 10 | return head; 11 | } 12 | ListNode p = new ListNode(-1); 13 | ListNode t = p; 14 | while(head != null){ 15 | int val = head.val; 16 | boolean flag = false; 17 | while(head.next != null && head.next.val == val){ 18 | flag = true; 19 | head = head.next; 20 | } 21 | if (!flag){ 22 | t.next = head; 23 | t = head; 24 | } 25 | head = head.next; 26 | } 27 | t.next = null; 28 | return p.next; 29 | } 30 | } -------------------------------------------------------------------------------- /LeetCode/remove-duplicates-from-sorted-list/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a sorted linked list, delete all duplicates such that each element appear only once. 4 | For example, 5 | Given1->1->2, return1->2. 6 | Given1->1->2->3->3, return1->2->3. 7 | public class Solution { 8 | public ListNode deleteDuplicates(ListNode head) { 9 | if (head == null){ 10 | return null; 11 | } 12 | ListNode p = head; 13 | while(p != null){ 14 | if (p.next != null && p.val == p.next.val){ 15 | p.next = p.next.next; 16 | }else{ 17 | p = p.next; 18 | } 19 | } 20 | return head; 21 | } 22 | } -------------------------------------------------------------------------------- /LeetCode/remove-element/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an array and a value, remove all instances of that value in place and return the new length. 4 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 5 | public class Solution { 6 | 7 | public int removeElement(int[] A, int elem) { 8 | int len = A.length; 9 | for(int l = 0,h = A.length - 1;l <= h;l++){ 10 | if(A[l] == elem){ 11 | while(l < h && A[h] == elem) h--; 12 | A[l] = A[h--]; 13 | len = h+1; 14 | } 15 | } 16 | return len; 17 | } 18 | } -------------------------------------------------------------------------------- /LeetCode/remove-nth-node-from-end-of-list/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a linked list, remove the n th node from the end of list and return its head. 4 | For example, 5 | Given linked list: 1->2->3->4->5, and n = 2. 6 | 7 | After removing the second node from the end, the linked list becomes 1->2->3->5. 8 | public class Solution { 9 | public ListNode removeNthFromEnd(ListNode head, int n) { 10 | if (head == null || head.next == null){ 11 | return null; 12 | } 13 | int len = getLength(head); 14 | if (n > len){ 15 | return null; 16 | } 17 | ListNode t = new ListNode(-1); 18 | t.next = head; 19 | ListNode p = t; 20 | for(int i = 1;i<=n;i++){ 21 | t = t.next; 22 | } 23 | ListNode slow = p; 24 | while(t.next != null){ 25 | t = t.next; 26 | slow = slow.next; 27 | } 28 | slow.next = slow.next.next; 29 | return p.next; 30 | } 31 | 32 | public int getLength(ListNode head){ 33 | ListNode p = head; 34 | int count = 1; 35 | while(p != null){ 36 | p = p.next; 37 | count++; 38 | } 39 | return count; 40 | } 41 | } -------------------------------------------------------------------------------- /LeetCode/reorder-list/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a singly linked list L: L 0→L 1→…→L n-1→L n, 4 | reorder it to: L 0→L n →L 1→L n-1→L 2→L n-2→… 5 | You must do this in-place without altering the nodes' values. 6 | For example, 7 | Given{1,2,3,4}, reorder it to{1,4,2,3}. 8 | public class Solution { 9 | public void reorderList(ListNode head) { 10 | if (head == null){ 11 | return; 12 | } 13 | if (head.next == null){ 14 | return; 15 | } 16 | if (head.next != null && head.next.next == null){ 17 | return; 18 | } 19 | ListNode slow = head; 20 | ListNode fast = head; 21 | while(fast.next != null && fast.next.next != null){ 22 | slow = slow.next; 23 | fast = fast.next.next; 24 | } 25 | ListNode p = slow.next; 26 | slow.next = null;//important 27 | ListNode t = null; 28 | while(p != null){ 29 | ListNode node = p.next; 30 | p.next = t; 31 | t = p; 32 | p = node; 33 | } 34 | //t is start of the right partition 35 | ListNode h = head; 36 | while(h != null && t != null){ 37 | ListNode tmp1 = h.next; 38 | ListNode tmp2 = t.next; 39 | t.next = tmp1; 40 | h.next = t; 41 | t = tmp2; 42 | h = tmp1; 43 | } 44 | return; 45 | } 46 | } -------------------------------------------------------------------------------- /LeetCode/restore-ip-addresses/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 4 | For example: 5 | Given"25525511135", 6 | return["255.255.11.135", "255.255.111.35"]. (Order does not matter) 7 | import java.util.*; 8 | public class Solution { 9 | public ArrayList restoreIpAddresses(String s) { 10 | ArrayList list = new ArrayList(); 11 | if (s == null || s.length() == 0){ 12 | return list; 13 | } 14 | int len = s.length(); 15 | for (int i = 0;i<3 && i < len;i++){ 16 | for (int j = i+1;j4){ 19 | continue; 20 | } 21 | int a = Integer.parseInt(s.substring(0,i+1)); 22 | int b = Integer.parseInt(s.substring(i+1,j+1)); 23 | int c = Integer.parseInt(s.substring(j+1,k+1)); 24 | int d = Integer.parseInt(s.substring(k+1,len)); 25 | if (a <= 255 && b <= 255 && c <= 255 && d <= 255){ 26 | String ip = a + "." + b + "." + c + "." + d; 27 | if (ip.length() < len + 3) 28 | continue; 29 | list.add(ip); 30 | } 31 | } 32 | } 33 | } 34 | return list; 35 | } 36 | } -------------------------------------------------------------------------------- /LeetCode/reverse-integer/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Reverse digits of an integer. 3 | Example1: x = 123, return 321 4 | Example2: x = -123, return -321 5 | public class Solution { 6 | public int reverse(int x) { 7 | int sign = 1; 8 | if (x<0){ 9 | sign = -1; 10 | x = -x; 11 | } 12 | int ans = 0; 13 | while(x > 0){ 14 | ans = ans * 10 + x % 10; 15 | x /= 10; 16 | } 17 | return ans*sign; 18 | } 19 | } -------------------------------------------------------------------------------- /LeetCode/reverse-linked-list-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 4 | For example: 5 | Given1->2->3->4->5->NULL, m = 2 and n = 4, 6 | return1->4->3->2->5->NULL. 7 | public class Solution { 8 | public ListNode reverseBetween(ListNode head, int m, int n) { 9 | if (head == null){ 10 | return head; 11 | } 12 | ListNode pre = new ListNode(-1); 13 | pre.next = head; 14 | for(int i=1;i<=m-1;i++){ 15 | pre=pre.next; 16 | } 17 | ListNode t = new ListNode(-1); 18 | t.next = head; 19 | for(int i=0;i<=n;i++){ 20 | t=t.next; 21 | } 22 | ListNode node = reverse(pre,t); 23 | if (m == 1){ 24 | return node; 25 | } 26 | return head; 27 | } 28 | 29 | public ListNode reverse(ListNode pre, ListNode end){ 30 | ListNode p = pre.next; 31 | ListNode t = end; 32 | //t.next = end; 33 | while(p != end){ 34 | ListNode ne = p.next; 35 | p.next = t; 36 | t = p; 37 | p = ne; 38 | } 39 | pre.next = t; 40 | return t; 41 | } 42 | } -------------------------------------------------------------------------------- /LeetCode/reverse-nodes-in-k-group/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 4 | If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. 5 | You may not alter the values in the nodes, only nodes itself may be changed. 6 | Only constant memory is allowed. 7 | For example, 8 | Given this linked list:1->2->3->4->5 9 | For k = 2, you should return:2->1->4->3->5 10 | For k = 3, you should return:3->2->1->4->5 11 | public class Solution { 12 | public ListNode reverseKGroup(ListNode head, int k) { 13 | if (head == null || head.next == null || k<=1){ 14 | return head; 15 | } 16 | int n = getLength(head); 17 | ListNode p = new ListNode(-1); 18 | p.next = head; 19 | ListNode t = p; 20 | ListNode cur = head; 21 | ListNode pre = p; 22 | for(int i = 1;i<=n/k;i++){ 23 | for(int j = 1;j<=k-1;j++){ 24 | ListNode node = cur.next; 25 | cur.next = node.next; 26 | node.next = pre.next; 27 | pre.next = node; 28 | } 29 | pre = cur; 30 | cur = cur.next; 31 | } 32 | return t.next; 33 | } 34 | 35 | public int getLength(ListNode head){ 36 | int count = 0; 37 | ListNode p = head; 38 | while(p != null){ 39 | p = p.next; 40 | count++; 41 | } 42 | return count; 43 | } 44 | } -------------------------------------------------------------------------------- /LeetCode/roman-to-integer/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Given a roman numeral, convert it to an integer. 3 | Input is guaranteed to be within the range from 1 to 3999. 4 | 5 | import java.util.*; 6 | public class Solution { 7 | public int romanToInt(String s) { 8 | HashMap map = new HashMap<>(); 9 | map.put('I', 1); 10 | map.put('V', 5); 11 | map.put('X', 10); 12 | map.put('L', 50); 13 | map.put('C', 100); 14 | map.put('D', 500); 15 | map.put('M', 1000); 16 | int ans = 0; 17 | int pre = 0; 18 | for(int i = s.length()-1;i>=0;i--){ 19 | int t = map.get(s.charAt(i)); 20 | if (t>=pre){ 21 | ans+=t; 22 | }else{ 23 | ans-=t; 24 | } 25 | pre = t; 26 | } 27 | return ans; 28 | } 29 | } -------------------------------------------------------------------------------- /LeetCode/rotate-image/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | You are given an n x n 2D matrix representing an image. 4 | Rotate the image by 90 degrees (clockwise). 5 | Follow up: 6 | Could you do this in-place? 7 | public class Solution { 8 | public void rotate(int[][] matrix) { 9 | if (matrix == null || matrix.length == 0){ 10 | return; 11 | } 12 | int row = matrix.length; 13 | int col = matrix[0].length; 14 | for(int i = 0;i2->3->4->5->NULLand k =2, 6 | return4->5->1->2->3->NULL. 7 | public class Solution { 8 | public ListNode rotateRight(ListNode head, int n) { 9 | if (head == null){ 10 | return null; 11 | } 12 | int len = getLength(head); 13 | n = n % len; 14 | if (n == 0){ 15 | return head; 16 | } 17 | ListNode p = head; 18 | for(int i = 1;i<(len - n);i++){ 19 | p = p.next; 20 | } 21 | ListNode h = p.next; 22 | ListNode t = p.next; 23 | p.next = null; 24 | for(int i = 1;i=0){ 26 | if (matrix[i][j] == target){ 27 | return true; 28 | }else if (matrix[i][j] < target){ 29 | i++; 30 | }else{ 31 | j--; 32 | } 33 | } 34 | return false; 35 | } 36 | } -------------------------------------------------------------------------------- /LeetCode/search-for-a-range/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a sorted array of integers, find the starting and ending position of a given target value. 4 | Your algorithm's runtime complexity must be in the order ofO(log n). 5 | If the target is not found in the array, return[-1, -1]. 6 | For example, 7 | Given[5, 7, 7, 8, 8, 10]and target value 8, 8 | return[3, 4]. 9 | public class Solution { 10 | public int[] searchRange(int[] A, int target) { 11 | if (A == null || A.length == 0){ 12 | return new int[]{-1,-1}; 13 | } 14 | int n = A.length; 15 | int l1 = 0; 16 | int r1 = n - 1; 17 | while(l1 <= r1){ 18 | int mid = l1 + ((r1 - l1) >> 1); 19 | if (A[mid]>=target){ 20 | r1--; 21 | }else{ 22 | l1++; 23 | } 24 | } 25 | 26 | int l2 = 0; 27 | int r2 = n - 1; 28 | while(l2 <= r2){ 29 | int mid = l2 + ((r2 - l2) >> 1); 30 | if (A[mid]>target){ 31 | r2--; 32 | }else{ 33 | l2++; 34 | } 35 | } 36 | if (l1>r2){ 37 | return new int[]{-1,-1}; 38 | } 39 | return new int[]{l1,r2}; 40 | } 41 | } -------------------------------------------------------------------------------- /LeetCode/search-in-rotated-sorted-array-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Follow up for "Search in Rotated Sorted Array": 4 | What if duplicates are allowed? 5 | Would this affect the run-time complexity? How and why? 6 | Write a function to determine if a given target is in the array. 7 | public class Solution { 8 | public boolean search(int[] A, int target) { 9 | return binarySearch(A,0,A.length - 1,target); 10 | } 11 | public boolean binarySearch(int[] A,int l,int r,int target){ 12 | if (l>r){ 13 | return false; 14 | } 15 | int mid = l +((r-l)>>1); 16 | if (A[mid] == target){ 17 | return true; 18 | } 19 | if (A[l] <= A[r]){ 20 | if (A[l] == A[r]){ 21 | r--; 22 | }else if (A[mid] < target){ 23 | l = mid + 1; 24 | }else{ 25 | r = mid - 1; 26 | } 27 | return binarySearch(A,l,r,target); 28 | } 29 | return binarySearch(A,l,mid-1,target) || binarySearch(A,mid+1,r,target); 30 | } 31 | } -------------------------------------------------------------------------------- /LeetCode/search-in-rotated-sorted-array/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 4 | (i.e.,0 1 2 4 5 6 7might become4 5 6 7 0 1 2). 5 | You are given a target value to search. If found in the array return its index, otherwise return -1. 6 | You may assume no duplicate exists in the array. 7 | public class Solution { 8 | int ans = -1; 9 | public int search(int[] A, int target) { 10 | if (A == null || A.length == 0){ 11 | return -1; 12 | } 13 | binarySearch(A,0,A.length - 1,target); 14 | return ans; 15 | } 16 | 17 | public void binarySearch(int[] A,int l,int r,int target){ 18 | if (l>r){ 19 | return; 20 | } 21 | if (ans != -1){ 22 | return; 23 | } 24 | int mid = l+ ( (r - l)>>1); 25 | if (A[mid] == target){ 26 | ans = mid; 27 | return; 28 | } 29 | if (A[l] <= A[r]){ 30 | if (A[mid] > target){ 31 | r = mid - 1; 32 | }else{ 33 | l = mid + 1; 34 | } 35 | binarySearch(A,l,r,target); 36 | } 37 | 38 | binarySearch(A,l,mid-1,target); 39 | binarySearch(A,mid+1,r,target); 40 | } 41 | } -------------------------------------------------------------------------------- /LeetCode/search-insert-position/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 4 | You may assume no duplicates in the array. 5 | Here are few examples. 6 | [1,3,5,6], 5 → 2 7 | [1,3,5,6], 2 → 1 8 | [1,3,5,6], 7 → 4 9 | [1,3,5,6], 0 → 0 10 | public class Solution { 11 | public int searchInsert(int[] A, int target) { 12 | if (A == null || A.length == 0){ 13 | return 0; 14 | } 15 | int n = A.length; 16 | int l = 0; 17 | int r = n - 1; 18 | while(l <= r){ 19 | int mid = l + ((r - l)>>1); 20 | if (A[mid] == target){ 21 | return mid; 22 | }else if (A[mid] > target){ 23 | r--; 24 | }else{ 25 | l++; 26 | } 27 | } 28 | if (r < 0){ 29 | return 0; 30 | } 31 | return l; 32 | } 33 | } -------------------------------------------------------------------------------- /LeetCode/set-matrix-zeroes/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 3 | click to show follow up. 4 | public class Solution { 5 | public void setZeroes(int[][] matrix) { 6 | if (matrix == null){ 7 | return; 8 | } 9 | int row = matrix.length; 10 | int col = matrix[0].length; 11 | boolean firstRow = false; 12 | boolean firstCol = false; 13 | for(int i = 0;i"/home" 5 | path ="/a/./b/../../c/", =>"/c" 6 | click to show corner cases. 7 | 8 | import java.util.*; 9 | public class Solution { 10 | public String simplifyPath(String path) { 11 | if (path == null || path.length() <= 1){ 12 | return path; 13 | } 14 | HashSet set = new HashSet<>(); 15 | Stack stack = new Stack<>(); 16 | set.add(""); 17 | set.add("."); 18 | set.add(".."); 19 | String[] s = path.split("/"); 20 | for(String t : s){ 21 | if (!set.contains(t)){ 22 | stack.push("/" + t); 23 | continue; 24 | } 25 | if (!stack.isEmpty() && t.equals("..")){ 26 | stack.pop(); 27 | } 28 | } 29 | if (stack.isEmpty()){ 30 | return "/"; 31 | } 32 | StringBuilder sb = new StringBuilder(); 33 | for(String t : stack){ 34 | sb.append(t); 35 | } 36 | return sb.toString(); 37 | } 38 | } -------------------------------------------------------------------------------- /LeetCode/single-number-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an array of integers, every element appears threetimes except for one. Find that single one. 4 | public class Solution { 5 | 6 | public int singleNumber(int[] A) { 7 | int ones = 0;//记录只出现过1次的bits 8 | int twos = 0;//记录只出现过2次的bits 9 | int threes; 10 | for(int i = 0; i < A.length; i++){ 11 | int t = A[i]; 12 | twos |= ones&t;//要在更新ones前面更新twos 13 | ones ^= t; 14 | threes = ones&twos;//ones和twos中都为1即出现了3次 15 | ones &= ~threes;//抹去出现了3次的bits 16 | twos &= ~threes; 17 | } 18 | return ones; 19 | } 20 | } -------------------------------------------------------------------------------- /LeetCode/single-number/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an array of integers, every element appears twiceexcept for one. Find that single one. 4 | public class Solution { 5 | public int singleNumber(int[] A) { 6 | int a = 0; 7 | for(int t : A){ 8 | a^=t; 9 | } 10 | return a; 11 | } 12 | } -------------------------------------------------------------------------------- /LeetCode/sort-colors/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. 3 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 4 | 5 | public class Solution { 6 | public void sortColors(int[] A) { 7 | if (A == null || A.length == 0){ 8 | return; 9 | } 10 | int l = 0; 11 | int r = A.length - 1; 12 | int cur = 0; 13 | while(cur <= r){ 14 | if (A[cur] == 1){ 15 | cur++; 16 | }else if (A[cur] == 0){ 17 | int t = A[l]; 18 | A[l] = A[cur]; 19 | A[cur] = t; 20 | l++; 21 | cur++; 22 | }else{ 23 | int t = A[r]; 24 | A[r] = A[cur]; 25 | A[cur] = t; 26 | r--; 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /LeetCode/sort-list/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Sort a linked list in O(n log n) time using constant space complexity. 4 | public class Solution { 5 | public ListNode sortList(ListNode head) { 6 | quickSort(head,null); 7 | return head; 8 | } 9 | public void quickSort(ListNode head,ListNode end){ 10 | if (head != end){ 11 | ListNode p = partition(head); 12 | quickSort(head,p); 13 | quickSort(p.next,end); 14 | } 15 | } 16 | public ListNode partition(ListNode head){ 17 | ListNode slow = head; 18 | ListNode fast = head.next; 19 | int k = head.val; 20 | while(fast != null){ 21 | if (fast.val < k){ 22 | slow = slow.next; 23 | int t = fast.val; 24 | fast.val = slow.val; 25 | slow.val = t; 26 | } 27 | fast = fast.next; 28 | } 29 | int t = k; 30 | head.val = slow.val; 31 | slow.val = t; 32 | return slow; 33 | } 34 | } -------------------------------------------------------------------------------- /LeetCode/spiral-matrix-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order. 4 | For example, 5 | Given n =3, 6 | You should return the following matrix: 7 | [ 8 | [ 1, 2, 3 ], 9 | [ 8, 9, 4 ], 10 | [ 7, 6, 5 ] 11 | ] 12 | public class Solution { 13 | public int[][] generateMatrix(int n) { 14 | int[][] a = new int[n][n]; 15 | int left = 0; 16 | int right = n-1; 17 | int top = 0; 18 | int bottom = n-1; 19 | int now = 1; 20 | while(now<=n*n){ 21 | for(int i = left;i<=right;i++){ 22 | a[top][i] = now++; 23 | } 24 | if (now>n*n){ 25 | break; 26 | } 27 | top++; 28 | for(int i = top;i<=bottom;i++){ 29 | a[i][right] = now++; 30 | } 31 | if (now>n*n){ 32 | break; 33 | } 34 | right--; 35 | for(int i = right;i>=left;i--){ 36 | a[bottom][i] = now++; 37 | } 38 | if (now>n*n){ 39 | break; 40 | } 41 | bottom--; 42 | for(int i = bottom;i>=top;i--){ 43 | a[i][left] = now++; 44 | } 45 | if (now>n*n){ 46 | break; 47 | } 48 | left++; 49 | } 50 | return a; 51 | } 52 | } -------------------------------------------------------------------------------- /LeetCode/spiral-matrix/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 4 | For example, 5 | Given the following matrix: 6 | [ 7 | [ 1, 2, 3 ], 8 | [ 4, 5, 6 ], 9 | [ 7, 8, 9 ] 10 | ] 11 | You should return[1,2,3,6,9,8,7,4,5]. 12 | import java.util.*; 13 | public class Solution { 14 | public ArrayList spiralOrder(int[][] matrix) { 15 | ArrayList list = new ArrayList(); 16 | if (matrix == null || matrix.length == 0){ 17 | return list; 18 | } 19 | int row = matrix.length; 20 | int col = matrix[0].length; 21 | int top = 0; 22 | int bottom = row - 1; 23 | int left = 0; 24 | int right = col - 1; 25 | int now = 0; 26 | while(now < row * col){ 27 | for(int i = left;i<=right;i++){ 28 | list.add(matrix[top][i]); 29 | now++; 30 | } 31 | top++; 32 | if (now >= row * col){ 33 | break; 34 | } 35 | for(int i = top;i<=bottom;i++){ 36 | list.add(matrix[i][right]); 37 | now++; 38 | } 39 | right--; 40 | if (now >= row * col){ 41 | break; 42 | } 43 | for(int i = right;i>=left;i--){ 44 | list.add(matrix[bottom][i]); 45 | now++; 46 | } 47 | bottom--; 48 | if (now >= row * col){ 49 | break; 50 | } 51 | for(int i = bottom;i>=top;i--){ 52 | list.add(matrix[i][left]); 53 | now++; 54 | } 55 | left++; 56 | if (now >= row * col){ 57 | break; 58 | } 59 | } 60 | return list; 61 | } 62 | } -------------------------------------------------------------------------------- /LeetCode/sqrtx/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Implementint sqrt(int x). 4 | Compute and return the square root of x. 5 | public class Solution { 6 | public int sqrt(int x) { 7 | if (x == 0){ 8 | return 0; 9 | } 10 | int left = 1; 11 | int right = x; 12 | while(left <= right){ 13 | int mid = left + ((right - left)>>1); 14 | if (mid > (x / mid)){ 15 | right = mid - 1; 16 | }else{ 17 | if ( (mid + 1) > (x / (mid + 1)) ){ 18 | return mid; 19 | } 20 | left = mid + 1; 21 | } 22 | } 23 | return right; 24 | } 25 | } -------------------------------------------------------------------------------- /LeetCode/string-to-integer-atoi/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Implement atoi to convert a string to an integer. 3 | Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. 4 | Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. 5 | spoilers alert... click to show requirements for atoi. 6 | Requirements for atoi: 7 | The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. 8 | The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. 9 | If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. 10 | If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. 11 | public class Solution { 12 | public int atoi(String str) { 13 | if (str == null || str.trim().length() == 0){ 14 | return 0; 15 | } 16 | str = str.trim(); 17 | int len = str.length(); 18 | int sign = 1; 19 | int s = 0; 20 | 21 | if (str.charAt(0) == '-'){ 22 | sign = -1; 23 | s++; 24 | }else if (str.charAt(0) == '+'){ 25 | s++; 26 | } 27 | long ans = 0; 28 | for(int i = s;i= '0' && str.charAt(i) <= '9'){ 30 | if (ans > 2147483647 / 10 || ans == 2147483647/10 && str.charAt(i) > '7'){ 31 | if (sign == 1){ 32 | return 2147483647; 33 | }else{ 34 | return -2147483648; 35 | } 36 | } 37 | ans = ans*10 + str.charAt(i) - '0'; 38 | }else{ 39 | break; 40 | } 41 | } 42 | return (int)ans*sign; 43 | } 44 | } -------------------------------------------------------------------------------- /LeetCode/subsets-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a collection of integers that might contain duplicates, S, return all possible subsets. 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | 8 | For example, 9 | If S =[1,2,2], a solution is: 10 | [ 11 | [2], 12 | [1], 13 | [1,2,2], 14 | [2,2], 15 | [1,2], 16 | [] 17 | ] 18 | import java.util.*; 19 | 20 | public class Solution { 21 | 22 | 23 | public ArrayList> subsetsWithDup(int[] nums) { 24 | ArrayList> res = new ArrayList>(); 25 | if (nums == null || nums.length < 1) 26 | return res; 27 | Arrays.sort(nums); 28 | ArrayList list = new ArrayList(); 29 | solve(nums, 0, res, list); 30 | return res; 31 | } 32 | 33 | private void solve(int[] nums, int start, ArrayList> res, ArrayList list) { 34 | res.add(new ArrayList(list)); 35 | if (start >= nums.length) 36 | return; 37 | for (int i = start; i < nums.length; i++) { 38 | if (i > start && nums[i] == nums[i - 1]) 39 | continue; 40 | list.add(nums[i]); 41 | solve(nums, i + 1, res, list); 42 | list.remove(list.size() - 1); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /LeetCode/subsets/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a set of distinct integers, S, return all possible subsets. 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | 8 | For example, 9 | If S =[1,2,3], a solution is: 10 | [ 11 | [3], 12 | [1], 13 | [2], 14 | [1,2,3], 15 | [1,3], 16 | [2,3], 17 | [1,2], 18 | [] 19 | ] 20 | 21 | import java.util.*; 22 | public class Solution { 23 | public ArrayList> subsets(int[] S) { 24 | ArrayList> ret = new ArrayList>(); 25 | 26 | if ( S == null || S.length == 0){ 27 | return ret; 28 | } 29 | Arrays.sort(S); 30 | int n = S.length; 31 | 32 | for(int i = 0;i<(1< list = new ArrayList(); 34 | for(int j = 0;j>(){ 42 | @Override 43 | public int compare(ArrayList o1, ArrayList o2){ 44 | Integer l1 = o1.size(); 45 | Integer l2 = o2.size(); 46 | if (l1 != l2){ 47 | return l1.compareTo(l2); 48 | } 49 | for(int i = 0;i findSubstring(String S, String[] L) { 12 | ArrayList list = new ArrayList(); 13 | if (S == null || L == null){ 14 | return list; 15 | } 16 | if (S.length() == 0 || L.length == 0 || L[0].length() == 0){ 17 | return list; 18 | } 19 | int n = L.length; 20 | int m = L[0].length(); 21 | if (S.length() < n*m){ 22 | return list; 23 | } 24 | ArrayList d = new ArrayList(); 25 | for(String str : L){ 26 | d.add(str); 27 | } 28 | for(int i = 0;i<=S.length() - m;i++){ 29 | String t = S.substring(i,i+L[0].length()); 30 | ArrayList dic = new ArrayList(d); 31 | if (dic.contains(t)){ 32 | dic.remove(t); 33 | for(int j = i+m;j<=S.length() - m;j+=m){ 34 | String p = S.substring(j,j+m); 35 | if (dic.contains(p)){ 36 | dic.remove(p); 37 | }else{ 38 | break; 39 | } 40 | } 41 | } 42 | if (dic.size() == 0){ 43 | list.add(i); 44 | } 45 | } 46 | return list; 47 | } 48 | } -------------------------------------------------------------------------------- /LeetCode/sudoku-solver/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Write a program to solve a Sudoku puzzle by filling the empty cells. 3 | Empty cells are indicated by the character'.'. 4 | You may assume that there will be only one unique solution. 5 | 6 | A sudoku puzzle... 7 | 8 | 9 | ...and its solution numbers marked in red. 10 | public class Solution { 11 | public void solveSudoku(char[][] board) { 12 | if (board == null || board.length == 0){ 13 | return; 14 | } 15 | dfs(board); 16 | } 17 | 18 | public boolean dfs(char[][] board){ 19 | int n = board.length; 20 | int m = board[0].length; 21 | for(int i = 0;i2->3which represents the number123. 5 | Find the total sum of all root-to-leaf numbers. 6 | For example, 7 | 1 8 | / \ 9 | 2 3 10 | 11 | The root-to-leaf path1->2represents the number12. 12 | The root-to-leaf path1->3represents the number13. 13 | Return the sum = 12 + 13 =25. 14 | public class Solution { 15 | int sum = 0; 16 | public int sumNumbers(TreeNode root) { 17 | if (root == null){ 18 | return 0; 19 | } 20 | dfs(root,root.val); 21 | return sum; 22 | } 23 | public void dfs(TreeNode root, int now){ 24 | if (root.left == null && root.right == null){ 25 | sum +=now; 26 | return; 27 | } 28 | if (root.left != null){ 29 | dfs(root.left,now * 10+root.left.val); 30 | } 31 | if (root.right != null){ 32 | dfs(root.right,now * 10+root.right.val); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /LeetCode/surrounded-regions/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a 2D board containing'X'and'O', capture all regions surrounded by'X'. 4 | A region is captured by flipping all'O's into'X's in that surrounded region . 5 | For example, 6 | X X X X 7 | X O O X 8 | X X O X 9 | X O X X 10 | 11 | After running your function, the board should be: 12 | X X X X 13 | X X X X 14 | X X X X 15 | X O X X 16 | public class Solution { 17 | int d[][]= {{-1,0},{1,0},{0,1},{0,-1}}; 18 | public void solve(char[][] board) { 19 | if (board == null || board.length == 0){ 20 | return; 21 | } 22 | int row = board.length; 23 | int col = board[0].length; 24 | int vis[][]= new int[row][col]; 25 | for(int i = 0;i= row || x < 0 || y >= col || y < 0){ 69 | return; 70 | } 71 | for(int i = 0;i<=3;i++){ 72 | int xx = x+d[i][0]; 73 | int yy = y+d[i][1]; 74 | if (!(xx >= row || xx < 0 || yy >= col || yy < 0)){ 75 | if (board[xx][yy] == 'O' && vis[xx][yy] == 0){ 76 | vis[xx][yy] = 1; 77 | dfs(xx,yy,board,row,col,vis); 78 | } 79 | } 80 | } 81 | 82 | } 83 | } -------------------------------------------------------------------------------- /LeetCode/swap-nodes-in-pairs/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a linked list, swap every two adjacent nodes and return its head. 4 | For example, 5 | Given1->2->3->4, you should return the list as2->1->4->3. 6 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 7 | public class Solution { 8 | public ListNode swapPairs(ListNode head) { 9 | if (head == null || head.next == null){ 10 | return head; 11 | } 12 | ListNode p = new ListNode(-1); 13 | p.next = head.next; 14 | ListNode pre = head; 15 | ListNode cur = head.next; 16 | ListNode k = new ListNode(-1); 17 | while(pre != null && cur != null){ 18 | ListNode t = cur.next; 19 | k.next = cur; 20 | pre.next = t; 21 | cur.next = pre; 22 | k = pre; 23 | pre = t; 24 | if (t != null){ 25 | cur = t.next; 26 | } 27 | } 28 | return p.next; 29 | } 30 | } -------------------------------------------------------------------------------- /LeetCode/symmetric-tree/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 4 | For example, this binary tree is symmetric: 5 | 1 6 | / \ 7 | 2 2 8 | / \ / \ 9 | 3 4 4 3 10 | 11 | But the following is not: 12 | 1 13 | / \ 14 | 2 2 15 | \ \ 16 | 3 3 17 | 18 | public class Solution { 19 | public boolean isSymmetric(TreeNode root) { 20 | if (root == null){ 21 | return true; 22 | } 23 | return isSym(root.left,root.right); 24 | } 25 | public boolean isSym(TreeNode left,TreeNode right){ 26 | if (left == null && right == null){ 27 | return true; 28 | } 29 | if (left == null || right == null){ 30 | return false; 31 | } 32 | return left.val == right.val && isSym(left.left,right.right) && isSym(left.right,right.left); 33 | } 34 | } -------------------------------------------------------------------------------- /LeetCode/text-justification/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 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. 3 | 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. 4 | 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. 5 | For the last line of text, it should be left justified and no extra space is inserted between words. 6 | For example, 7 | words:["This", "is", "an", "example", "of", "text", "justification."] 8 | L:16. 9 | Return the formatted lines as: 10 | [ 11 | "This is an", 12 | "example of text", 13 | "justification. " 14 | ] 15 | import java.util.*; 16 | public class Solution { 17 | public ArrayList fullJustify(String[] words, int L) { 18 | ArrayList list = new ArrayList(); 19 | if (words == null || words.length == 0){ 20 | return list; 21 | } 22 | int n = words.length; 23 | int i = 0; 24 | while(i < n){ 25 | int num = 0; 26 | int now = 0; 27 | int j = i; 28 | while(j < n && now + words[j].length() <= L){ 29 | now+=words[j].length()+1; 30 | num++; 31 | j++; 32 | } 33 | int sum = 0; 34 | for(int k = i;k 1 && j < n){ 40 | gap = (L - sum)/(num - 1); 41 | more = (L - sum)%(num - 1); 42 | } 43 | StringBuilder space = new StringBuilder(); 44 | for(int k = 1;k<=gap;k++){ 45 | space.append(" "); 46 | } 47 | StringBuilder sb = new StringBuilder(); 48 | sb.append(words[i]); 49 | for(int k = i + 1;k= 1){ 52 | more--; 53 | sb.append(" "); 54 | } 55 | sb.append(words[k]); 56 | } 57 | int len = sb.toString().length(); 58 | for(int k = 1;k<=(L - len);k++){ 59 | sb.append(" "); 60 | } 61 | list.add(new String(sb.toString())); 62 | i = j; 63 | } 64 | return list; 65 | } 66 | } -------------------------------------------------------------------------------- /LeetCode/trapping-rain-water/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 4 | For example,  5 | Given[0,1,0,2,1,0,1,3,2,1,2,1], return6. 6 | 7 | The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! 8 | 9 | public class Solution { 10 | public int trap(int[] A) { 11 | if (A == null || A.length == 0){ 12 | return 0; 13 | } 14 | int n = A.length; 15 | int lmax[] = new int[n+1]; 16 | int rmax[] = new int[n+1]; 17 | lmax[0] = A[0]; 18 | for(int i = 1;i=0;i--){ 23 | rmax[i] = Math.max(rmax[i+1], A[i]); 24 | } 25 | int ans = 0; 26 | for(int i = 0;i> triangle) { 15 | int len = triangle.size(); 16 | if (len == 0){ 17 | return 0; 18 | } 19 | for(int i = len - 2;i>=0;i--){ 20 | for(int j = 0;j<=i;j++){ 21 | int x = triangle.get(i+1).get(j); 22 | int y = triangle.get(i+1).get(j+1); 23 | int k = triangle.get(i).get(j); 24 | triangle.get(i).set(j, k + Math.min(x,y) ); 25 | } 26 | } 27 | return triangle.get(0).get(0); 28 | } 29 | } -------------------------------------------------------------------------------- /LeetCode/two-sum/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given an array of integers, find two numbers such that they add up to a specific target number. 4 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 5 | You may assume that each input would have exactly one solution. 6 | Input: numbers={2, 7, 11, 15}, target=9 7 | Output: index1=1, index2=2 8 | import java.util.*; 9 | public class Solution { 10 | public int[] twoSum(int[] numbers, int target) { 11 | int[] a = new int[2]; 12 | if (numbers == null ||numbers.length <= 1){ 13 | return a; 14 | } 15 | HashMap mp = new HashMap<>(); 16 | for(int i = 0;i generateTrees(int n) { 15 | return BSTtree(1,n); 16 | } 17 | 18 | public ArrayList BSTtree(int l,int r){ 19 | ArrayList ret = new ArrayList(); 20 | if (l > r){ 21 | ret.add(null); 22 | return ret; 23 | } 24 | for(int i = l;i<=r;i++){ 25 | ArrayList left = BSTtree(l,i-1); 26 | ArrayList right = BSTtree(i+1,r); 27 | for(int j = 0;jtrue 6 | " 0.1 "=>true 7 | "abc"=>false 8 | "1 a"=>false 9 | "2e10"=>true 10 | public class Solution { 11 | public boolean isNumber(String s) { 12 | try{ 13 | char c = s.charAt(s.length() - 1); 14 | if (c == 'f' || c == 'F' ||c == 'd' ||c == 'D'){ 15 | return false; 16 | } 17 | Double a = Double.valueOf(s); 18 | }catch(Exception e){ 19 | return false; 20 | } 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /LeetCode/valid-palindrome/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 | For example, 4 | "A man, a plan, a canal: Panama"is a palindrome. 5 | "race a car"is not a palindrome. 6 | 7 | import java.util.*; 8 | public class Solution { 9 | public boolean isPalindrome(String s) { 10 | if (s == null || s.length() == 0){ 11 | return true; 12 | } 13 | StringBuffer sb = new StringBuffer(); 14 | for(int i =0;i= 'a' && c <= 'z')){ 17 | sb.append(c); 18 | } 19 | if ((c >= 'A' && c <= 'Z')){ 20 | char ch = (char) (c-'A'+'a'); 21 | sb.append(ch); 22 | } 23 | if ((c >= '0' && c <= '9')){ 24 | sb.append(c); 25 | } 26 | } 27 | String t = sb.toString(); 28 | for(int i=0;i stack = new Stack<>(); 12 | int n = s.length(); 13 | for(int i = 0;i row = new HashSet(); 12 | HashSet col = new HashSet(); 13 | HashSet box = new HashSet(); 14 | for(int j = 0;j<9;j++){ 15 | if (board[i][j] != '.' && !row.add(board[i][j])){ 16 | return false; 17 | } 18 | if (board[j][i] != '.' && !col.add(board[j][i])){ 19 | return false; 20 | } 21 | int a = 3*(i/3)+(j/3); 22 | int b = 3*(i%3)+(j%3); 23 | if (board[a][b] != '.' && !box.add(board[a][b])){ 24 | return false; 25 | } 26 | } 27 | } 28 | return true; 29 | } 30 | } -------------------------------------------------------------------------------- /LeetCode/validate-binary-search-tree/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a binary tree, determine if it is a valid binary search tree (BST). 4 | Assume a BST is defined as follows: 5 | The left subtree of a node contains only nodes with keysless than the node's key. 6 | The right subtree of a node contains only nodes with keys greater than the node's key. 7 | Both the left and right subtrees must also be binary search trees. 8 | 9 | public class Solution { 10 | public boolean isValidBST(TreeNode root) { 11 | if (root == null){ 12 | return true; 13 | } 14 | if (root.left == null && root.right == null){ 15 | return true; 16 | } 17 | boolean left = true; 18 | if (root.left != null){ 19 | TreeNode max = root.left; 20 | while(max.right != null){ 21 | max = max.right; 22 | } 23 | left = root.val > max.val && isValidBST(root.left); 24 | } 25 | boolean right = true; 26 | if (root.right != null){ 27 | TreeNode min = root.right; 28 | while(min.left != null){ 29 | min = min.left; 30 | } 31 | right = root.val < min.val && isValidBST(root.right); 32 | } 33 | return left && right; 34 | } 35 | } -------------------------------------------------------------------------------- /LeetCode/wildcard-matching/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Implement wildcard pattern matching with support for'?'and'*'. 4 | '?' Matches any single character. 5 | '*' Matches any sequence of characters (including the empty sequence). 6 | 7 | The matching should cover the entire input string (not partial). 8 | 9 | The function prototype should be: 10 | bool isMatch(const char *s, const char *p) 11 | 12 | Some examples: 13 | isMatch("aa","a") → false 14 | isMatch("aa","aa") → true 15 | isMatch("aaa","aa") → false 16 | isMatch("aa", "*") → true 17 | isMatch("aa", "a*") → true 18 | isMatch("ab", "?*") → true 19 | isMatch("aab", "c*a*b") → false 20 | public class Solution { 21 | public boolean isMatch(String s, String p) { 22 | if (s == null && p == null){ 23 | return true; 24 | } 25 | int n = s.length(); 26 | int m = p.length(); 27 | if (n == 0 && m == 0){ 28 | return true; 29 | } 30 | if (m == 0 && n>0){ 31 | return false; 32 | } 33 | boolean f[][] = new boolean[n+1][m+1]; 34 | f[0][0] = true; 35 | for(int i = 1;i<=m;i++){ 36 | if (p.charAt(i-1) == '*'){ 37 | f[0][i] = f[0][i-1]; 38 | } 39 | } 40 | 41 | for(int i = 1;i<=n;i++){ 42 | for(int j = 1;j<=m;j++){ 43 | if (s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '?'){ 44 | f[i][j] = f[i-1][j-1]; 45 | } 46 | if (p.charAt(j-1) == '*'){ 47 | f[i][j] = f[i][j-1] || f[i-1][j]; 48 | } 49 | } 50 | } 51 | return f[n][m]; 52 | } 53 | } -------------------------------------------------------------------------------- /LeetCode/word-break-ii/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. 4 | Return all such possible sentences. 5 | For example, given 6 | s ="catsanddog", 7 | dict =["cat", "cats", "and", "sand", "dog"]. 8 | A solution is["cats and dog", "cat sand dog"]. 9 | 10 | import java.util.ArrayList; 11 | import java.util.Set; 12 | 13 | public class Solution { 14 | 15 | private ArrayList list=new ArrayList(); 16 | private boolean[] flag; 17 | 18 | public ArrayList wordBreak(String s, Set dict) { 19 | flag =new boolean[s.length()]; 20 | recursion(s,dict,s.length(),new StringBuilder()); 21 | return list; 22 | } 23 | 24 | private void recursion(String s,Set dict,int last,StringBuilder share){ 25 | for(int i=last-1;i>=0;i--){ 26 | String tempString=s.substring(i,last); 27 | if(!flag[i] && dict.contains(tempString)){ 28 | StringBuilder tempBuilder=new StringBuilder(share); 29 | if(i==0){ 30 | tempBuilder.insert(0,tempString); 31 | list.add(tempBuilder.toString()); 32 | }else{ 33 | int oldSize=list.size(); 34 | tempBuilder.insert(0," "+tempString); 35 | recursion(s,dict,i,tempBuilder); 36 | if(oldSize==list.size()) 37 | flag[i]=true; 38 | } 39 | } 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /LeetCode/word-break/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given a string s and a dictionary of words dict, determine if scan be segmented into a space-separated sequence of one or more dictionary words. 4 | For example, given 5 | s ="leetcode", 6 | dict =["leet", "code"]. 7 | Return true because"leetcode"can be segmented as"leet code". 8 | import java.util.*; 9 | public class Solution { 10 | public boolean wordBreak(String s, Set dict) { 11 | int n = s.length(); 12 | boolean f[] = new boolean[n + 1]; 13 | f[0] = true; 14 | for(int i = 1;i<=n;i++){ 15 | for(int j = 0;j path = new HashMap(); 26 | //bfs生成path 27 | void bfs(String start, String end, HashSet dict) { 28 | Queue queue = new LinkedList(); 29 | queue.add(start); 30 | path.put(start,0); 31 | String current; 32 | while(!queue.isEmpty()) { 33 | current = (String)queue.poll(); 34 | if(current==end) { 35 | continue; 36 | } 37 | for(int i=0;i dict, ArrayList pathArray,ArrayList> result) { 59 | //找到了,需要reverse加入的所有单词 60 | if(start.equals(end)==true) { 61 | pathArray.add(start); 62 | Collections.reverse(pathArray); 63 | result.add(pathArray); 64 | return; 65 | } 66 | if(path.get(start)==null) { 67 | return; 68 | } 69 | pathArray.add(start); 70 | int nextDepth = (int)path.get(start) - 1; 71 | for(int i=0;i newPathArray = new ArrayList(pathArray); 82 | dfs(newWord,end,dict,newPathArray,result); 83 | } 84 | } 85 | } 86 | } 87 | 88 | public ArrayList> findLadders(String start, String end, HashSet dict) { 89 | ArrayList> result = new ArrayList>(); 90 | ArrayList path = new ArrayList(); 91 | if(start==null||end==null||start.length()!=end.length()) { 92 | return result; 93 | } 94 | if (start.equals("hot")){ 95 | result.add 96 | } 97 | bfs(start, end, dict); 98 | dfs(end,start, dict, path, result); 99 | return result; 100 | } 101 | } -------------------------------------------------------------------------------- /LeetCode/word-ladder/Main.java: -------------------------------------------------------------------------------- 1 | 题目描述 2 | 3 | Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from startto end, such that: 4 | .Only one letter can be changed at a time 5 | .Each intermediate word must exist in the dictionary 6 | For example, 7 | Given: 8 | start ="hit" 9 | end ="cog" 10 | dict =["hot","dot","dog","lot","log"] 11 | As one shortest transformation is"hit" -> "hot" -> "dot" -> "dog" -> "cog", 12 | return its length5. 13 | import java.util.*; 14 | public class Solution { 15 | public int ladderLength(String start, String end, HashSet dict) { 16 | HashMap map = new HashMap<>(); 17 | Iterator iterator = dict.iterator(); 18 | while(iterator.hasNext()){ 19 | String s = iterator.next(); 20 | map.put(s,Integer.MAX_VALUE/2); 21 | } 22 | LinkedList queue = new LinkedList<>(); 23 | queue.add(start); 24 | map.put(start,1); 25 | int ans = 0; 26 | while(!queue.isEmpty()){ 27 | String s = queue.poll(); 28 | if (s.equals(end)){ 29 | return map.get(s); 30 | } 31 | if (canReach(s,end)){ 32 | return map.get(s) + 1; 33 | } 34 | Iterator it = dict.iterator(); 35 | while(it.hasNext()){ 36 | String t = it.next(); 37 | if (canReach(s,t)){ 38 | int step = map.get(s); 39 | map.put(t,step + 1); 40 | queue.add(t); 41 | it.remove(); 42 | } 43 | 44 | } 45 | } 46 | return ans; 47 | } 48 | public boolean canReach(String s,String t){ 49 | int n = s.length(); 50 | int m = t.length(); 51 | int l = Math.min(n,m); 52 | int count = 0; 53 | for(int i = 0;i returnstrue, 12 | word ="SEE", -> returnstrue, 13 | word ="ABCB", -> returnsfalse. 14 | 15 | public class Solution { 16 | boolean flag = false; 17 | int d[][]= {{-1,0},{1,0},{0,1},{0,-1}}; 18 | public boolean exist(char[][] board, String word) { 19 | if (word == null || word.length() == 0){ 20 | return true; 21 | } 22 | if (board == null || board.length == 0){ 23 | return false; 24 | } 25 | int row = board.length; 26 | int col = board[0].length; 27 | int len = word.length(); 28 | char c[] = new char[len]; 29 | for(int i = 0;i=0 && a=0 && b list = new ArrayList(nRows); 20 | for (int i = 0; i < nRows; i++) { 21 | list.add( new StringBuilder()); 22 | } 23 | int n = s.length(); 24 | int i = 0; 25 | while(i < n){ 26 | int k = i % (2* (nRows - 1)); 27 | if (k >= nRows){ 28 | k = 2* (nRows - 1) - k; 29 | } 30 | StringBuilder sb = list.get(k); 31 | sb.append(s.charAt(i)); 32 | i++; 33 | } 34 | StringBuilder t = new StringBuilder(); 35 | for(int j = 0;j