├── .gitignore ├── note ├── 1014 │ └── README.md ├── 0011 │ ├── water.png │ └── README.md ├── 0004 │ ├── my_draw.jpg │ └── README.md ├── 0031 │ └── README.md ├── 0058 │ └── README.md ├── 0007 │ └── README.md ├── 0104 │ └── README.md ├── 0069 │ └── README.md ├── 0119 │ └── README.md ├── 0083 │ └── README.md ├── 0070 │ └── README.md ├── 0050 │ └── README.md ├── 0035 │ └── README.md ├── 0088 │ └── README.md ├── 0112 │ └── README.md ├── 0021 │ └── README.md ├── 16_11 │ └── README.md ├── 0014 │ └── README.md ├── 0118 │ └── README.md ├── 0003 │ └── README.md ├── 0121 │ └── README.md ├── 0543 │ └── README.md ├── 0049 │ └── README.md ├── 0066 │ └── README.md ├── 0067 │ └── README.md ├── 0028 │ └── README.md ├── 0100 │ └── README.md ├── 0019 │ └── README.md ├── 0002 │ └── README.md ├── 0016 │ └── README.md ├── 0110 │ └── README.md ├── 0122 │ └── README.md ├── 0033 │ └── README.md ├── 0020 │ └── README.md ├── 0038 │ └── README.md ├── 0001 │ └── README.md ├── 0108 │ └── README.md ├── 0009 │ └── README.md ├── 0015 │ └── README.md ├── 0043 │ └── README.md ├── 0024 │ └── README.md ├── 0063 │ └── README.md ├── 0056 │ └── README.md ├── 0057 │ └── README.md ├── 0554 │ └── README.md ├── 0053 │ └── README.md ├── 0026 │ └── README.md ├── 0111 │ └── README.md ├── 0027 │ └── README.md ├── 0022 │ └── README.md ├── 0029 │ └── README.md ├── 0017 │ └── README.md ├── 0101 │ └── README.md ├── 0025 │ └── README.md ├── 0107 │ └── README.md ├── 0012 │ └── README.md ├── 0013 │ └── README.md ├── 0023 │ └── README.md └── 0209 │ └── README.md ├── src └── com │ └── blankj │ ├── easy │ ├── _0069 │ │ └── Solution.java │ ├── _0070 │ │ └── Solution.java │ ├── _0058 │ │ └── Solution.java │ ├── _0122 │ │ └── Solution.java │ ├── _0007 │ │ └── Solution.java │ ├── _0119 │ │ └── Solution.java │ ├── _0104 │ │ └── Solution.java │ ├── _0121 │ │ └── Solution.java │ ├── _0027 │ │ └── Solution.java │ ├── _0112 │ │ └── Solution.java │ ├── _0543 │ │ └── Solution.java │ ├── _0028 │ │ └── Solution.java │ ├── _0026 │ │ └── Solution.java │ ├── _0014 │ │ └── Solution.java │ ├── _16_11 │ │ └── Solution.java │ ├── _0083 │ │ └── Solution.java │ ├── _0035 │ │ └── Solution.java │ ├── _0108 │ │ └── Solution.java │ ├── _0088 │ │ └── Solution.java │ ├── _0110 │ │ └── Solution.java │ ├── _0066 │ │ └── Solution.java │ ├── _0100 │ │ └── Solution.java │ ├── _0020 │ │ └── Solution.java │ ├── _0038 │ │ └── Solution.java │ ├── _0118 │ │ └── Solution.java │ ├── _0021 │ │ └── Solution.java │ ├── _0013 │ │ └── Solution.java │ ├── _0107 │ │ └── Solution.java │ ├── _0009 │ │ └── Solution.java │ ├── _0001 │ │ └── Solution.java │ ├── _0111 │ │ └── Solution.java │ ├── _0053 │ │ └── Solution.java │ ├── _0067 │ │ └── Solution.java │ └── _0101 │ │ └── Solution.java │ ├── medium │ ├── _0050 │ │ └── Solution.java │ ├── _1014 │ │ └── Solution.java │ ├── _0011 │ │ └── Solution.java │ ├── _0012 │ │ └── Solution.java │ ├── _0033 │ │ └── Solution.java │ ├── _0029 │ │ └── Solution.java │ ├── _0019 │ │ └── Solution.java │ ├── _0003 │ │ └── Solution.java │ ├── _0024 │ │ └── Solution.java │ ├── _0016 │ │ └── Solution.java │ ├── _0002 │ │ └── Solution.java │ ├── _0043 │ │ └── Solution.java │ ├── _0067 │ │ └── Solution.java │ ├── _0049 │ │ └── Solution.java │ ├── _0554 │ │ └── Solution.java │ ├── _0056 │ │ └── Solution.java │ ├── _0015 │ │ └── Solution.java │ ├── _0008 │ │ └── Solution.java │ ├── _0022 │ │ └── Solution.java │ ├── _0017 │ │ └── Solution.java │ ├── _0006 │ │ └── Solution.java │ ├── _0005 │ │ └── Solution.java │ └── _0209 │ │ └── Solution.java │ ├── hard │ ├── _0025 │ │ └── Solution.java │ ├── _0004 │ │ └── Solution.java │ ├── _0057 │ │ └── Solution.java │ ├── _0068 │ │ └── Solution.java │ ├── _0023 │ │ └── Solution.java │ ├── _1028 │ │ └── Solution.java │ ├── _0030 │ │ └── Solution.java │ └── _0010 │ │ └── Solution.java │ └── structure │ ├── ListNode.java │ ├── Interval.java │ └── TreeNode.java └── .github └── FUNDING.yml /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.iml 3 | .idea 4 | out 5 | -------------------------------------------------------------------------------- /note/0011/water.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Blankj/awesome-java-leetcode/HEAD/note/0011/water.png -------------------------------------------------------------------------------- /note/0004/my_draw.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Blankj/awesome-java-leetcode/HEAD/note/0004/my_draw.jpg -------------------------------------------------------------------------------- /src/com/blankj/easy/_0069/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._069; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/08 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int mySqrt(int x) { 13 | long n = x; 14 | while (n * n > x) { 15 | n = (n + x / n) >> 1; 16 | } 17 | return (int) n; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Solution solution = new Solution(); 22 | System.out.println(solution.mySqrt(10)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0070/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._070; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/09 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int climbStairs(int n) { 13 | int a = 1, b = 1; 14 | while (--n > 0) { 15 | b += a; 16 | a = b - a; 17 | } 18 | return b; 19 | } 20 | 21 | public static void main(String[] args) { 22 | Solution solution = new Solution(); 23 | System.out.println(solution.climbStairs(3)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: https://raw.githubusercontent.com/Blankj/AndroidUtilCode/master/art/donate.png 13 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0058/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._058; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/05 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int lengthOfLastWord(String s) { 13 | int p = s.length() - 1; 14 | while (p >= 0 && s.charAt(p) == ' ') p--; 15 | int end = p; 16 | while (p >= 0 && s.charAt(p) != ' ') p--; 17 | return end - p; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Solution solution = new Solution(); 22 | System.out.println(solution.lengthOfLastWord("word ")); 23 | System.out.println(solution.lengthOfLastWord("hello world")); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0122/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._122; 2 | 3 | 4 | /** 5 | *
6 | * author: Blankj 7 | * blog : http://blankj.com 8 | * time : 2017/10/11 9 | * desc : 10 | *11 | */ 12 | public class Solution { 13 | public int maxProfit(int[] prices) { 14 | int max = 0; 15 | for (int i = 1; i < prices.length; ++i) { 16 | if (prices[i] > prices[i - 1]) max += prices[i] - prices[i - 1]; 17 | } 18 | return max; 19 | } 20 | 21 | public static void main(String[] args) { 22 | Solution solution = new Solution(); 23 | System.out.println(solution.maxProfit(new int[]{7, 1, 5, 3, 6, 4})); 24 | System.out.println(solution.maxProfit(new int[]{7, 6, 4, 3, 1})); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0050/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._050; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/18 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public double myPow(double x, int n) { 13 | if (n < 0) return helper(1 / x, -n); 14 | return helper(x, n); 15 | } 16 | 17 | private double helper(double x, int n) { 18 | if (n == 0) return 1; 19 | if (n == 1) return x; 20 | double d = helper(x, n >>> 1); 21 | if (n % 2 == 0) return d * d; 22 | return d * d * x; 23 | } 24 | 25 | public static void main(String[] args) { 26 | Solution solution = new Solution(); 27 | System.out.println(solution.myPow(8.88023, 3)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_1014/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._1014; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2020/06/18 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | 13 | public int maxScoreSightseeingPair(int[] A) { 14 | int ans = 0, cur = A[0] + 0; 15 | for (int j = 1; j < A.length; j++) { 16 | ans = Math.max(ans, cur + A[j] - j); // 计算当前最大得分 17 | cur = Math.max(cur, A[j] + j); // 更新最大的 A[i] + i 18 | } 19 | return ans; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Solution solution = new Solution(); 24 | int[] A = new int[]{8, 1, 5, 2, 6}; 25 | System.out.println(solution.maxScoreSightseeingPair(A)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0007/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._007; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/19 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int reverse(int x) { 13 | long res = 0; 14 | for (; x != 0; x /= 10) 15 | res = res * 10 + x % 10; 16 | return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res; 17 | } 18 | 19 | public static void main(String[] args) { 20 | Solution solution = new Solution(); 21 | System.out.println(solution.reverse(123)); 22 | System.out.println(solution.reverse(-123)); 23 | System.out.println(solution.reverse(100)); 24 | System.out.println(solution.reverse(1000000003)); 25 | } 26 | } -------------------------------------------------------------------------------- /src/com/blankj/easy/_0119/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._119; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /** 8 | *
9 | * author: Blankj 10 | * blog : http://blankj.com 11 | * time : 2017/10/11 12 | * desc : 13 | *14 | */ 15 | public class Solution { 16 | public List
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/09 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public int maxDepth(TreeNode root) { 16 | if (root == null) return 0; 17 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 18 | } 19 | 20 | public static void main(String[] args) { 21 | Solution solution = new Solution(); 22 | System.out.println(solution.maxDepth(TreeNode.createTestData("[]"))); 23 | System.out.println(solution.maxDepth(TreeNode.createTestData("[1,2,2,3,4,4,3]"))); 24 | System.out.println(solution.maxDepth(TreeNode.createTestData("[9,-42,-42,null,76,76,null,null,13,null,13]"))); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0121/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._121; 2 | 3 | 4 | /** 5 | *
6 | * author: Blankj 7 | * blog : http://blankj.com 8 | * time : 2017/10/11 9 | * desc : 10 | *11 | */ 12 | public class Solution { 13 | public int maxProfit(int[] prices) { 14 | int max = 0, minPrice = Integer.MAX_VALUE; 15 | for (int i = 0; i < prices.length; ++i) { 16 | if (prices[i] < minPrice) minPrice = prices[i]; 17 | int delta = prices[i] - minPrice; 18 | if (delta > max) max = delta; 19 | } 20 | return max; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Solution solution = new Solution(); 25 | System.out.println(solution.maxProfit(new int[]{7, 1, 5, 3, 6, 4})); 26 | System.out.println(solution.maxProfit(new int[]{7, 6, 4, 3, 1})); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0027/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._027; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/31 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int removeElement(int[] nums, int val) { 13 | int tail = 0; 14 | for (int i = 0, len = nums.length; i < len; ++i) { 15 | if (nums[i] != val) { 16 | nums[tail++] = nums[i]; 17 | } 18 | } 19 | return tail; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Solution solution = new Solution(); 24 | int[] data = new int[]{0, 3, 1, 1, 2, 3, 3, 3}; 25 | int len = solution.removeElement(data, 3); 26 | for (int i = 0; i < len; i++) { 27 | System.out.print(data[i] + (i == len - 1 ? "" : ", ")); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0112/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._112; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/11 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public boolean hasPathSum(TreeNode root, int sum) { 16 | if (root == null) return false; 17 | if (root.left == null && root.right == null) return sum == root.val; 18 | return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); 19 | } 20 | 21 | public static void main(String[] args) { 22 | Solution solution = new Solution(); 23 | TreeNode testData = TreeNode.createTestData("[5,4,8,11,null,13,4,7,2,null,null,null,1]"); 24 | TreeNode.print(testData); 25 | System.out.println(solution.hasPathSum(testData, 22)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0543/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._543; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/13 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | int max = 0; 16 | 17 | public int diameterOfBinaryTree(TreeNode root) { 18 | helper(root); 19 | return max; 20 | } 21 | 22 | private int helper(TreeNode root) { 23 | if (root == null) return 0; 24 | int l = helper(root.left); 25 | int r = helper(root.right); 26 | if (l + r > max) max = l + r; 27 | return Math.max(l, r) + 1; 28 | } 29 | 30 | public static void main(String[] args) { 31 | Solution solution = new Solution(); 32 | System.out.println(solution.diameterOfBinaryTree(TreeNode.createTestData("[1,2,3,4,5]"))); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0028/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._028; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/01 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int strStr(String haystack, String needle) { 13 | int l1 = haystack.length(), l2 = needle.length(); 14 | if (l1 < l2) return -1; 15 | for (int i = 0; ; i++) { 16 | if (i + l2 > l1) return -1; 17 | for (int j = 0; ; j++) { 18 | if (j == l2) return i; 19 | if (haystack.charAt(i + j) != needle.charAt(j)) break; 20 | } 21 | } 22 | } 23 | 24 | public static void main(String[] args) { 25 | Solution solution = new Solution(); 26 | System.out.println(solution.strStr("12345", "23")); 27 | System.out.println(solution.strStr("12345", "")); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0011/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._011; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/23 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int maxArea(int[] height) { 13 | int l = 0, r = height.length - 1; 14 | int max = 0, h = 0; 15 | while (l < r) { 16 | h = Math.min(height[l], height[r]); 17 | max = Math.max(max, (r - l) * h); 18 | while (height[l] <= h && l < r) ++l; 19 | while (height[r] <= h && l < r) --r; 20 | } 21 | return max; 22 | } 23 | 24 | public static void main(String[] args) { 25 | Solution solution = new Solution(); 26 | System.out.println(solution.maxArea(new int[]{1, 2, 4, 3})); // 4 27 | System.out.println(solution.maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));// 49 28 | } 29 | } -------------------------------------------------------------------------------- /note/0031/README.md: -------------------------------------------------------------------------------- 1 | # [Next Permutation][title] 2 | 3 | ## Description 4 | 5 | Implement **next permutation**, which rearranges numbers into the lexicographically next greater permutation of numbers. 6 | 7 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 8 | 9 | The replacement must be **in-place** and use only constant extra memory. 10 | 11 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 12 | 13 | `1,2,3` → `1,3,2` 14 | `3,2,1` → `1,2,3` 15 | `1,1,5` → `1,5,1` 16 | 17 | **Tags:** Array 18 | 19 | 20 | ## 思路 21 | 22 | 题意是 23 | 24 | ```java 25 | 26 | ``` 27 | 28 | 29 | ## 结语 30 | 31 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 32 | 33 | 34 | 35 | [title]: https://leetcode.com/problems/next-permutation 36 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 37 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0012/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._012; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2018/01/25 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String intToRoman(int num) { 13 | String M[] = {"", "M", "MM", "MMM"}; 14 | String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 15 | String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 16 | String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 17 | return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10]; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Solution solution = new Solution(); 22 | System.out.println(solution.intToRoman(621));// DCXXI 23 | System.out.println(solution.intToRoman(348));// CCCXLVIII 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0026/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._026; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/30 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int removeDuplicates(int[] nums) { 13 | int len = nums.length; 14 | if (len <= 1) return len; 15 | int tail = 1; 16 | for (int i = 1; i < len; ++i) { 17 | if (nums[i - 1] != nums[i]) { 18 | nums[tail++] = nums[i]; 19 | } 20 | } 21 | return tail; 22 | } 23 | 24 | public static void main(String[] args) { 25 | Solution solution = new Solution(); 26 | int[] data = new int[]{0, 1, 1, 2, 3, 3, 3}; 27 | int len = solution.removeDuplicates(data); 28 | for (int i = 0; i < len; i++) { 29 | System.out.print(data[i] + (i == len - 1 ? "" : ", ")); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0014/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._014; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/26 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String longestCommonPrefix(String[] strs) { 13 | int len = strs.length; 14 | if (len == 0) return ""; 15 | int minLen = 0x7fffffff; 16 | for (String str : strs) minLen = Math.min(minLen, str.length()); 17 | for (int j = 0; j < minLen; ++j) 18 | for (int i = 1; i < len; ++i) 19 | if (strs[0].charAt(j) != strs[i].charAt(j)) 20 | return strs[0].substring(0, j); 21 | return strs[0].substring(0, minLen); 22 | } 23 | 24 | public static void main(String[] args) { 25 | Solution solution = new Solution(); 26 | System.out.println(solution.longestCommonPrefix(new String[]{"abc", "abcd", "ab"})); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_16_11/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._16_11; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2020/07/08 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public int[] divingBoard(int shorter, int longer, int k) { 15 | if (k == 0) { 16 | return new int[0]; 17 | } 18 | if (shorter == longer) { 19 | return new int[]{shorter * k}; 20 | } 21 | int[] ans = new int[k + 1]; 22 | int st = k * shorter;// 等差数列的首项 23 | int delta = longer - shorter;// 公差 24 | for (int i = 0; i <= k; i++) { 25 | ans[i] = st + i * delta; 26 | } 27 | return ans; 28 | } 29 | 30 | public static void main(String[] args) { 31 | Solution solution = new Solution(); 32 | System.out.println(Arrays.toString(solution.divingBoard(1, 2, 3))); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0083/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._083; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/05/10 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode deleteDuplicates(ListNode head) { 15 | if (head == null || head.next == null) return head; 16 | ListNode curr = head; 17 | while (curr.next != null) { 18 | if (curr.next.val == curr.val) { 19 | curr.next = curr.next.next; 20 | } else { 21 | curr = curr.next; 22 | } 23 | } 24 | return head; 25 | } 26 | 27 | public static void main(String[] args) { 28 | Solution solution = new Solution(); 29 | ListNode.print(solution.deleteDuplicates(ListNode.createTestData("[1,1,2]"))); 30 | ListNode.print(solution.deleteDuplicates(ListNode.createTestData("[1,1,2,3,3]"))); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0035/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._035; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/02 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int searchInsert(int[] nums, int target) { 13 | int left = 0, right = nums.length - 1, mid = (right + left) >> 1; 14 | while (left <= right) { 15 | if (target <= nums[mid]) right = mid - 1; 16 | else left = mid + 1; 17 | mid = (right + left) >> 1; 18 | } 19 | return left; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Solution solution = new Solution(); 24 | int[] nums = new int[]{1, 3, 5, 6}; 25 | System.out.println(solution.searchInsert(nums, 5)); 26 | System.out.println(solution.searchInsert(nums, 2)); 27 | System.out.println(solution.searchInsert(nums, 7)); 28 | System.out.println(solution.searchInsert(nums, 0)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0033/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._033; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/16 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int search(int[] nums, int target) { 13 | int l = 0, r = nums.length - 1, mid; 14 | while (l <= r) { 15 | mid = l + r >>> 1; 16 | if (nums[mid] == target) return mid; 17 | else if (nums[mid] >= nums[l]) { 18 | if (nums[l] <= target && target < nums[mid]) r = mid - 1; 19 | else l = mid + 1; 20 | } else { 21 | if (nums[mid] < target && target <= nums[r]) l = mid + 1; 22 | else r = mid - 1; 23 | } 24 | } 25 | return -1; 26 | } 27 | 28 | public static void main(String[] args) { 29 | Solution solution = new Solution(); 30 | System.out.println(solution.search(new int[]{2, 1}, 1)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0108/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._108; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/09 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public TreeNode sortedArrayToBST(int[] nums) { 16 | if (nums == null || nums.length == 0) return null; 17 | return helper(nums, 0, nums.length - 1); 18 | } 19 | 20 | private TreeNode helper(int[] nums, int left, int right) { 21 | if (left > right) return null; 22 | int mid = (left + right) >>> 1; 23 | TreeNode node = new TreeNode(nums[mid]); 24 | node.left = helper(nums, left, mid - 1); 25 | node.right = helper(nums, mid + 1, right); 26 | return node; 27 | } 28 | 29 | public static void main(String[] args) { 30 | Solution solution = new Solution(); 31 | TreeNode.print(solution.sortedArrayToBST(new int[]{0, 1, 2, 3, 4, 5, 6, 7})); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0088/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._088; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/06/01 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public void merge(int[] nums1, int m, int[] nums2, int n) { 15 | int p = m-- + n-- - 1; 16 | while (m >= 0 && n >= 0) 17 | nums1[p--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; 18 | while (n >= 0) 19 | nums1[p--] = nums2[n--]; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Solution solution = new Solution(); 24 | int[] nums1 = new int[10]; 25 | for (int i = 0; i < 5; ++i) { 26 | nums1[i] = 2 * i; 27 | } 28 | int[] nums2 = new int[5]; 29 | for (int i = 0; i < 5; ++i) { 30 | nums2[i] = 2 * i + 1; 31 | } 32 | solution.merge(nums1, 5, nums2, 5); 33 | System.out.println(Arrays.toString(nums1)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0110/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._110; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/09 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public boolean isBalanced(TreeNode root) { 16 | return helper(root) != -1; 17 | } 18 | 19 | private int helper(TreeNode node) { 20 | if (node == null) return 0; 21 | int l = helper(node.left); 22 | if (l == -1) return -1; 23 | int r = helper(node.right); 24 | if (r == -1) return -1; 25 | if (Math.abs(l - r) > 1) return -1; 26 | return 1 + Math.max(l, r); 27 | } 28 | 29 | public static void main(String[] args) { 30 | Solution solution = new Solution(); 31 | TreeNode testData = TreeNode.createTestData("[1,2,2,3,3,3,3,4,4,4,4,4,4,null,null,5,5]"); 32 | TreeNode.print(testData); 33 | System.out.println(solution.isBalanced(testData)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0066/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._066; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/05/06 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public int[] plusOne(int[] digits) { 15 | int p = digits.length - 1; 16 | if (digits[p] < 9) { 17 | digits[p] = ++digits[p]; 18 | } else { 19 | do { 20 | digits[p--] = 0; 21 | } while (p >= 0 && digits[p] == 9); 22 | if (digits[0] != 0) { 23 | ++digits[p]; 24 | } else { 25 | digits = new int[digits.length + 1]; 26 | digits[0] = 1; 27 | } 28 | } 29 | return digits; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Solution solution = new Solution(); 34 | int[] digits = solution.plusOne(new int[]{9, 9, 9}); 35 | System.out.println(Arrays.toString(digits)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0100/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._100; 2 | 3 | 4 | import com.blankj.structure.TreeNode; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/08 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public boolean isSameTree(TreeNode p, TreeNode q) { 16 | if (p == null || q == null) return p == q; 17 | if (p.val != q.val) return false; 18 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 19 | } 20 | 21 | public static void main(String[] args) { 22 | Solution solution = new Solution(); 23 | System.out.println(solution.isSameTree( 24 | TreeNode.createTestData("[1,2,2,null,3,null,3]"), 25 | TreeNode.createTestData("[1,2,2,null,3,null,3]")) 26 | ); 27 | System.out.println(solution.isSameTree( 28 | TreeNode.createTestData("[1,2,2,null,3,null,3]"), 29 | TreeNode.createTestData("[1,2,2,null,3,null,null]")) 30 | ); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0029/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._029; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2018/01/31 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int divide(int dividend, int divisor) { 13 | if (dividend == Integer.MIN_VALUE && divisor == -1) { 14 | return Integer.MAX_VALUE; 15 | } 16 | long dvd = Math.abs((long) dividend); 17 | long dvr = Math.abs((long) divisor); 18 | int res = 0; 19 | while (dvd >= dvr) { 20 | long temp = dvr, multiple = 1; 21 | while (dvd >= temp << 1) { 22 | temp <<= 1; 23 | multiple <<= 1; 24 | } 25 | dvd -= temp; 26 | res += multiple; 27 | } 28 | return (dividend < 0) ^ (divisor < 0) ? -res : res; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Solution solution = new Solution(); 33 | System.out.println(solution.divide(-2147483648, 1)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0020/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._020; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/28 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public boolean isValid(String s) { 13 | char[] stack = new char[s.length() + 1]; 14 | int top = 1; 15 | for (char c : s.toCharArray()) { 16 | if (c == '(' || c == '[' || c == '{') { 17 | stack[top++] = c; 18 | } else if (c == ')' && stack[--top] != '(') { 19 | return false; 20 | } else if (c == ']' && stack[--top] != '[') { 21 | return false; 22 | } else if (c == '}' && stack[--top] != '{') { 23 | return false; 24 | } 25 | } 26 | return top == 1; 27 | } 28 | 29 | public static void main(String[] args) { 30 | Solution solution = new Solution(); 31 | System.out.println(solution.isValid("()[]{}({[]})")); 32 | System.out.println(solution.isValid("(])]")); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0019/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._019; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/04/27 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode removeNthFromEnd(ListNode head, int n) { 15 | ListNode pre = head; 16 | ListNode afterPreN = head; 17 | while (n-- != 0) { 18 | afterPreN = afterPreN.next; 19 | } 20 | if (afterPreN != null) { 21 | while (afterPreN.next != null) { 22 | pre = pre.next; 23 | afterPreN = afterPreN.next; 24 | } 25 | pre.next = pre.next.next; 26 | } else { 27 | head = head.next; 28 | } 29 | return head; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Solution solution = new Solution(); 34 | ListNode.print(solution.removeNthFromEnd(ListNode.createTestData("[1,2,3,4,5]"), 2)); 35 | ListNode.print(solution.removeNthFromEnd(ListNode.createTestData("[1]"), 1)); 36 | } 37 | } -------------------------------------------------------------------------------- /src/com/blankj/easy/_0038/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._038; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/03 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String countAndSay(int n) { 13 | String str = "1"; 14 | while (--n > 0) { 15 | int times = 1; 16 | StringBuilder sb = new StringBuilder(); 17 | char[] chars = str.toCharArray(); 18 | int len = chars.length; 19 | for (int j = 1; j < len; j++) { 20 | if (chars[j - 1] == chars[j]) { 21 | times++; 22 | } else { 23 | sb.append(times).append(chars[j - 1]); 24 | times = 1; 25 | } 26 | } 27 | str = sb.append(times).append(chars[len - 1]).toString(); 28 | } 29 | return str; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Solution solution = new Solution(); 34 | for (int i = 1; i < 6; i++) { 35 | System.out.println(solution.countAndSay(i)); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0118/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._118; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Collections; 6 | import java.util.List; 7 | 8 | /** 9 | *
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2017/10/11 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/11 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int lengthOfLongestSubstring(String s) { 13 | int len; 14 | if (s == null || (len = s.length()) == 0) return 0; 15 | int preP = 0, max = 0; 16 | int[] hash = new int[128]; 17 | for (int i = 0; i < len; ++i) { 18 | char c = s.charAt(i); 19 | if (hash[c] > preP) { 20 | preP = hash[c]; 21 | } 22 | int l = i - preP + 1; 23 | hash[c] = i + 1; 24 | if (l > max) max = l; 25 | } 26 | return max; 27 | } 28 | 29 | public static void main(String[] args) { 30 | Solution solution = new Solution(); 31 | System.out.println(solution.lengthOfLongestSubstring("abcabcbb")); 32 | System.out.println(solution.lengthOfLongestSubstring("bbbbb")); 33 | System.out.println(solution.lengthOfLongestSubstring("pwwkew")); 34 | System.out.println(solution.lengthOfLongestSubstring("Abcabcbb")); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0021/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._021; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/04/29 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 15 | ListNode head = new ListNode(0); 16 | ListNode temp = head; 17 | while (l1 != null && l2 != null) { 18 | if (l1.val < l2.val) { 19 | temp.next = l1; 20 | l1 = l1.next; 21 | } else { 22 | temp.next = l2; 23 | l2 = l2.next; 24 | } 25 | temp = temp.next; 26 | } 27 | temp.next = l1 != null ? l1 : l2; 28 | return head.next; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Solution solution = new Solution(); 33 | ListNode listNode0 = ListNode.createTestData("[1,3,5,7,9]"); 34 | ListNode listNode1 = ListNode.createTestData("[2,4,6,8,10]"); 35 | ListNode.print(listNode0); 36 | ListNode.print(listNode1); 37 | ListNode.print(solution.mergeTwoLists(listNode0, listNode1)); 38 | } 39 | } -------------------------------------------------------------------------------- /src/com/blankj/medium/_0024/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._024; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2018/01/31 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | // public ListNode swapPairs(ListNode head) { 15 | // if (head == null || head.next == null) return head; 16 | // ListNode node = head.next; 17 | // head.next = swapPairs(node.next); 18 | // node.next = head; 19 | // return node; 20 | // } 21 | 22 | public ListNode swapPairs(ListNode head) { 23 | ListNode preHead = new ListNode(0), cur = preHead; 24 | preHead.next = head; 25 | while (cur.next != null && cur.next.next != null) { 26 | ListNode temp = cur.next.next; 27 | cur.next.next = temp.next; 28 | temp.next = cur.next; 29 | cur.next = temp; 30 | cur = cur.next.next; 31 | } 32 | return preHead.next; 33 | } 34 | 35 | public static void main(String[] args) { 36 | Solution solution = new Solution(); 37 | ListNode.print(solution.swapPairs(ListNode.createTestData("[1,2,3,4]"))); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0013/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._013; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/04/25 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | public int romanToInt(String s) { 16 | Map
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2018/01/25 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public int threeSumClosest(int[] nums, int target) { 15 | int delta = 0x7fffffff, res = 0; 16 | Arrays.sort(nums); 17 | int len = nums.length - 2; 18 | for (int i = 0; i < len; i++) { 19 | int left = i + 1, right = nums.length - 1; 20 | while (left < right) { 21 | int sum = nums[i] + nums[left] + nums[right]; 22 | int curDelta = Math.abs(sum - target); 23 | if (curDelta == 0) return sum; 24 | if (curDelta < delta) { 25 | delta = curDelta; 26 | res = sum; 27 | } 28 | if (sum > target) --right; 29 | else ++left; 30 | } 31 | } 32 | return res; 33 | } 34 | 35 | public static void main(String[] args) { 36 | Solution solution = new Solution(); 37 | System.out.println(solution.threeSumClosest(new int[]{-1, 2, 1, -4}, 1)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /note/0058/README.md: -------------------------------------------------------------------------------- 1 | # [Length of Last Word][title] 2 | 3 | ## Description 4 | 5 | Given a string *s* consists of upper/lower-case alphabets and empty space characters `' '`, return the length of last word in the string. 6 | 7 | If the last word does not exist, return 0. 8 | 9 | **Note:** A word is defined as a character sequence consists of non-space characters only. 10 | 11 | **Example:** 12 | 13 | ``` 14 | Input: "Hello World" 15 | Output: 5 16 | ``` 17 | 18 | **Tags:** String 19 | 20 | 21 | ## 思路 22 | 23 | 题意是让你从一个只包含大小字母和空格字符的字符串中得到最后一个单词的长度,很简单,我们倒序遍历,先得到最后一个非空格字符的索引,然后再得到它前面的空格字符索引,两者相减即可。当然,我们使用 API 来完成这件事更加方便,只需一行代码 `return s.trim().length() - s.trim().lastIndexOf(" ") - 1;`,但我相信作者出这道题的目的肯定不是考你 API 的使用,所以我们还是用自己的思路来实现。 24 | 25 | ```java 26 | class Solution { 27 | public int lengthOfLastWord(String s) { 28 | int p = s.length() - 1; 29 | while (p >= 0 && s.charAt(p) == ' ') p--; 30 | int end = p; 31 | while (p >= 0 && s.charAt(p) != ' ') p--; 32 | return end - p; 33 | } 34 | } 35 | ``` 36 | 37 | 38 | ## 结语 39 | 40 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 41 | 42 | 43 | 44 | [title]: https://leetcode.com/problems/length-of-last-word 45 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 46 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0002/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._002; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | /** 6 | *
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/10/11 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 15 | ListNode node = new ListNode(0); 16 | ListNode n1 = l1, n2 = l2, t = node; 17 | int sum = 0; 18 | while (n1 != null || n2 != null) { 19 | sum /= 10; 20 | if (n1 != null) { 21 | sum += n1.val; 22 | n1 = n1.next; 23 | } 24 | if (n2 != null) { 25 | sum += n2.val; 26 | n2 = n2.next; 27 | } 28 | t.next = new ListNode(sum % 10); 29 | t = t.next; 30 | } 31 | if (sum / 10 != 0) t.next = new ListNode(1); 32 | return node.next; 33 | } 34 | 35 | public static void main(String[] args) { 36 | Solution solution = new Solution(); 37 | ListNode.print(solution.addTwoNumbers( 38 | ListNode.createTestData("[2,4,3]"), 39 | ListNode.createTestData("[5,6,4]") 40 | )); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /note/0007/README.md: -------------------------------------------------------------------------------- 1 | # [Reverse Integer][title] 2 | 3 | ## Description 4 | 5 | Given a 32-bit signed integer, reverse digits of an integer. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 123 11 | Output: 321 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: -123 18 | Output: -321 19 | ``` 20 | 21 | **Example 3:** 22 | 23 | ``` 24 | Input: 120 25 | Output: 21 26 | ``` 27 | 28 | **Note:** 29 | 30 | Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 31 | 32 | **Tags:** Math 33 | 34 | 35 | ## 思路 36 | 37 | 题意是给你一个整型数,求它的逆序整型数,而且有个小坑点,当它的逆序整型数溢出的话,那么就返回 0,用我们代码表示的话可以求得结果保存在 long 中,最后把结果和整型的两个范围比较即可。 38 | 39 | ```java 40 | class Solution { 41 | public int reverse(int x) { 42 | long res = 0; 43 | for (; x != 0; x /= 10) 44 | res = res * 10 + x % 10; 45 | return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res; 46 | } 47 | } 48 | ``` 49 | 50 | 51 | ## 结语 52 | 53 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 54 | 55 | 56 | 57 | [title]: https://leetcode.com/problems/reverse-integer 58 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 59 | -------------------------------------------------------------------------------- /note/0104/README.md: -------------------------------------------------------------------------------- 1 | # [Maximum Depth of Binary Tree][title] 2 | 3 | ## Description 4 | 5 | Given a binary tree, find its maximum depth. 6 | 7 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 8 | 9 | **Note:** A leaf is a node with no children. 10 | 11 | **Example:** 12 | 13 | Given binary tree `[3,9,20,null,null,15,7]`, 14 | 15 | ``` 16 | 3 17 | / \ 18 | 9 20 19 | / \ 20 | 15 7 21 | ``` 22 | 23 | return its depth = 3. 24 | 25 | **Tags:** Tree, Depth-first Search 26 | 27 | 28 | ## 思路 29 | 30 | 题意是找到二叉树的最大深度,很明显,深搜即可,每深入一次节点加一即可,然后取左右子树的最大深度。 31 | 32 | ```java 33 | /** 34 | * Definition for a binary tree node. 35 | * public class TreeNode { 36 | * int val; 37 | * TreeNode left; 38 | * TreeNode right; 39 | * TreeNode(int x) { val = x; } 40 | * } 41 | */ 42 | class Solution { 43 | public int maxDepth(TreeNode root) { 44 | if (root == null) return 0; 45 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 46 | } 47 | } 48 | ``` 49 | 50 | 51 | ## 结语 52 | 53 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 54 | 55 | 56 | 57 | [title]: https://leetcode.com/problems/maximum-depth-of-binary-tree 58 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 59 | -------------------------------------------------------------------------------- /note/0069/README.md: -------------------------------------------------------------------------------- 1 | # [Sqrt(x)][title] 2 | 3 | ## Description 4 | 5 | Implement `int sqrt(int x)`. 6 | 7 | Compute and return the square root of *x*, where *x* is guaranteed to be a non-negative integer. 8 | 9 | Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: 4 15 | Output: 2 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: 8 22 | Output: 2 23 | Explanation: The square root of 8 is 2.82842..., and since 24 | the decimal part is truncated, 2 is returned. 25 | ``` 26 | 27 | **Tags:** Binary Search, Math 28 | 29 | 30 | ## 思路 31 | 32 | 题意是求平方根,参考 [牛顿迭代法求平方根](https://wenku.baidu.com/view/6b74c622bcd126fff7050bfe.html),然后再参考维基百科的 [Integer square root](https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division) 即可。 33 | 34 | ```java 35 | class Solution { 36 | public int mySqrt(int x) { 37 | long n = x; 38 | while (n * n > x) { 39 | n = (n + x / n) >> 1; 40 | } 41 | return (int) n; 42 | } 43 | } 44 | ``` 45 | 46 | 47 | ## 结语 48 | 49 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 50 | 51 | 52 | 53 | [title]: https://leetcode.com/problems/sqrtx 54 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 55 | -------------------------------------------------------------------------------- /note/0119/README.md: -------------------------------------------------------------------------------- 1 | # [Pascal's Triangle II][title] 2 | 3 | ## Description 4 | 5 | Given a non-negative index *k* where *k* ≤ 33, return the *k*th index row of the Pascal's triangle. 6 | 7 | Note that the row index starts from 0. 8 | 9 |  10 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 11 | 12 | **Example:** 13 | 14 | ``` 15 | Input: 3 16 | Output: [1,3,3,1] 17 | ``` 18 | 19 | **Follow up:** 20 | 21 | Could you optimize your algorithm to use only *O*(*k*) extra space? 22 | 23 | **Tags:** Array 24 | 25 | 26 | ## 思路 27 | 28 | 题意是指定输出帕斯卡尔三角形的某一行,模拟即可,优化后的代码如下所示。 29 | 30 | ```java 31 | class Solution { 32 | public List
11 | * author: Blankj 12 | * blog : http://blankj.com 13 | * time : 2017/10/09 14 | * desc : 15 | *16 | */ 17 | public class Solution { 18 | public List
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2017/10/16 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | public ListNode reverseKGroup(ListNode head, int k) { 15 | if (head == null || k == 1) return head; 16 | ListNode node = new ListNode(0), pre = node; 17 | node.next = head; 18 | for (int i = 1; head != null; ++i) { 19 | if (i % k == 0) { 20 | pre = reverse(pre, head.next); 21 | head = pre.next; 22 | } else { 23 | head = head.next; 24 | } 25 | } 26 | return node.next; 27 | } 28 | 29 | private ListNode reverse(ListNode pre, ListNode next) { 30 | ListNode head = pre.next; 31 | ListNode move = head.next; 32 | while (move != next) { 33 | head.next = move.next; 34 | move.next = pre.next; 35 | pre.next = move; 36 | move = head.next; 37 | } 38 | return head; 39 | } 40 | 41 | public static void main(String[] args) { 42 | Solution solution = new Solution(); 43 | ListNode.print(solution.reverseKGroup(ListNode.createTestData("[1,2,3,4,5,6,7,8]"), 3)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0009/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._009; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/24 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | // public boolean isPalindrome(int x) { 13 | // if (x < 0) return false; 14 | // int copyX = x, reverse = 0; 15 | // while (copyX > 0) { 16 | // reverse = reverse * 10 + copyX % 10; 17 | // copyX /= 10; 18 | // } 19 | // return x == reverse; 20 | // } 21 | 22 | public boolean isPalindrome(int x) { 23 | if (x < 0 || (x != 0 && x % 10 == 0)) return false; 24 | int halfReverseX = 0; 25 | while (x > halfReverseX) { 26 | halfReverseX = halfReverseX * 10 + x % 10; 27 | x /= 10; 28 | } 29 | return halfReverseX == x || halfReverseX / 10 == x; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Solution solution = new Solution(); 34 | System.out.println(solution.isPalindrome(-1)); 35 | System.out.println(solution.isPalindrome(10010)); 36 | 37 | System.out.println(solution.isPalindrome(0)); 38 | System.out.println(solution.isPalindrome(11)); 39 | System.out.println(solution.isPalindrome(111)); 40 | System.out.println(solution.isPalindrome(222222222)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /note/0083/README.md: -------------------------------------------------------------------------------- 1 | # [Remove Duplicates from Sorted List][title] 2 | 3 | ## Description 4 | 5 | Given a sorted linked list, delete all duplicates such that each element appear only *once*. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 1->1->2 11 | Output: 1->2 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: 1->1->2->3->3 18 | Output: 1->2->3 19 | ``` 20 | 21 | **Tags:** Linked List 22 | 23 | 24 | ## 思路 25 | 26 | 题意是删除链表中重复的元素,很简单,我们只需要遍历一遍链表,遇到链表中相邻元素相同时,把当前指针指向下下个元素即可。 27 | 28 | ```java 29 | /** 30 | * Definition for singly-linked list. 31 | * public class ListNode { 32 | * int val; 33 | * ListNode next; 34 | * ListNode(int x) { val = x; } 35 | * } 36 | */ 37 | class Solution { 38 | public ListNode deleteDuplicates(ListNode head) { 39 | if (head == null || head.next == null) return head; 40 | ListNode curr = head; 41 | while (curr.next != null) { 42 | if (curr.next.val == curr.val) { 43 | curr.next = curr.next.next; 44 | } else { 45 | curr = curr.next; 46 | } 47 | } 48 | return head; 49 | } 50 | } 51 | ``` 52 | 53 | 54 | ## 结语 55 | 56 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 57 | 58 | 59 | 60 | [title]: https://leetcode.com/problems/remove-duplicates-from-sorted-list 61 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 62 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0043/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._043; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/17 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String multiply(String num1, String num2) { 13 | if (num1.equals("0") || num2.equals("0")) return "0"; 14 | int l1 = num1.length(), l2 = num2.length(), l = l1 + l2; 15 | char[] ans = new char[l]; 16 | char[] c1 = num1.toCharArray(); 17 | char[] c2 = num2.toCharArray(); 18 | for (int i = l1 - 1; i >= 0; --i) { 19 | int c = c1[i] - '0'; 20 | for (int j = l2 - 1; j >= 0; --j) { 21 | ans[i + j + 1] += c * (c2[j] - '0'); 22 | } 23 | } 24 | for (int i = l - 1; i > 0; --i) { 25 | if (ans[i] > 9) { 26 | ans[i - 1] += ans[i] / 10; 27 | ans[i] %= 10; 28 | } 29 | } 30 | StringBuilder sb = new StringBuilder(); 31 | int i = 0; 32 | for (; ; ++i) if (ans[i] != 0) break; 33 | for (; i < ans.length; ++i) sb.append((char) (ans[i] + '0')); 34 | return sb.toString(); 35 | } 36 | 37 | public static void main(String[] args) { 38 | Solution solution = new Solution(); 39 | System.out.println(solution.multiply("132", "19")); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /note/0070/README.md: -------------------------------------------------------------------------------- 1 | # [Climbing Stairs][title] 2 | 3 | ## Description 4 | 5 | You are climbing a stair case. It takes *n* steps to reach to the top. 6 | 7 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 8 | 9 | **Note:** Given *n* will be a positive integer. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: 2 15 | Output: 2 16 | Explanation: There are two ways to climb to the top. 17 | 1. 1 step + 1 step 18 | 2. 2 steps 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: 3 25 | Output: 3 26 | Explanation: There are three ways to climb to the top. 27 | 1. 1 step + 1 step + 1 step 28 | 2. 1 step + 2 steps 29 | 3. 2 steps + 1 step 30 | ``` 31 | 32 | **Tags:** Dynamic Programming 33 | 34 | 35 | ## 思路 36 | 37 | 题意是爬楼梯,每次你只能爬一步或者两步,问到顶层共有多少种方案。我们假设到顶层共有 `f(n)` 种,那么 `f(n) = f(n - 1) + f(n - 2)` 肯定是成立的,意思就是我们迈向顶层的最后一步是在倒数第一级台阶或者在倒数第二级台阶。算法我对空间复杂度进行了优化,因为在迭代过程中只需要两个变量即可。 38 | 39 | ```java 40 | class Solution { 41 | public int climbStairs(int n) { 42 | int a = 1, b = 1; 43 | while (--n > 0) { 44 | b += a; 45 | a = b - a; 46 | } 47 | return b; 48 | } 49 | } 50 | ``` 51 | 52 | 53 | ## 结语 54 | 55 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 56 | 57 | 58 | 59 | [title]: https://leetcode.com/problems/climbing-stairs 60 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 61 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0001/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._001; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/04/21 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | // public int[] twoSum(int[] nums, int target) { 16 | // for (int i = 0; i < nums.length; ++i) { 17 | // for (int j = i + 1; j < nums.length; ++j) { 18 | // if (nums[i] + nums[j] == target) { 19 | // return new int[]{i, j}; 20 | // } 21 | // } 22 | // } 23 | // return null; 24 | // } 25 | 26 | public int[] twoSum(int[] nums, int target) { 27 | int len = nums.length; 28 | HashMap
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2020/07/07 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 13 | int m = obstacleGrid.length, n = obstacleGrid[0].length; 14 | int[][] dp = new int[m][n]; 15 | // 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法, 16 | // 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0; 17 | for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) { 18 | dp[i][0] = 1; 19 | } 20 | for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) { 21 | dp[0][j] = 1; 22 | } 23 | 24 | for (int i = 1; i < m; i++) { 25 | for (int j = 1; j < n; j++) { 26 | if (obstacleGrid[i][j] == 0) { 27 | // 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 28 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 29 | } 30 | } 31 | } 32 | return dp[m - 1][n - 1]; 33 | } 34 | 35 | public static void main(String[] args) { 36 | Solution solution = new Solution(); 37 | int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}; 38 | System.out.println(solution.uniquePathsWithObstacles(obstacleGrid)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /note/0050/README.md: -------------------------------------------------------------------------------- 1 | # [Pow(x, n)][title] 2 | 3 | ## Description 4 | 5 | Implement [pow(*x*, *n*)](http://www.cplusplus.com/reference/valarray/pow/), which calculates *x* raised to the power *n* (xn). 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 2.00000, 10 11 | Output: 1024.00000 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: 2.10000, 3 18 | Output: 9.26100 19 | ``` 20 | 21 | **Example 3:** 22 | 23 | ``` 24 | Input: 2.00000, -2 25 | Output: 0.25000 26 | Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 27 | ``` 28 | 29 | **Note:** 30 | 31 | - -100.0 < *x* < 100.0 32 | - *n* is a 32-bit signed integer, within the range [−231, 231 − 1] 33 | 34 | **Tags:** Math, Binary Search 35 | 36 | 37 | ## 思路 38 | 39 | 题意是让你计算 `x^n`,如果直接计算肯定会超时,那么我们可以想到可以使用二分法来降低时间复杂度。 40 | 41 | ```java 42 | class Solution { 43 | public double myPow(double x, int n) { 44 | if (n < 0) return helper(1 / x, -n); 45 | return helper(x, n); 46 | } 47 | 48 | private double helper(double x, int n) { 49 | if (n == 0) return 1; 50 | if (n == 1) return x; 51 | double d = helper(x, n >>> 1); 52 | if (n % 2 == 0) return d * d; 53 | return d * d * x; 54 | } 55 | } 56 | ``` 57 | 58 | 59 | ## 结语 60 | 61 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 62 | 63 | 64 | 65 | [title]: https://leetcode.com/problems/powx-n 66 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 67 | -------------------------------------------------------------------------------- /note/0035/README.md: -------------------------------------------------------------------------------- 1 | # [Search Insert Position][title] 2 | 3 | ## Description 4 | 5 | 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. 6 | 7 | You may assume no duplicates in the array. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: [1,3,5,6], 5 13 | Output: 2 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: [1,3,5,6], 2 20 | Output: 1 21 | ``` 22 | 23 | **Example 3:** 24 | 25 | ``` 26 | Input: [1,3,5,6], 7 27 | Output: 4 28 | ``` 29 | 30 | **Example 1:** 31 | 32 | ``` 33 | Input: [1,3,5,6], 0 34 | Output: 0 35 | ``` 36 | 37 | **Tags:** Array, Binary Search 38 | 39 | 40 | ## 思路 41 | 42 | 题意是让你从一个没有重复元素的已排序数组中找到插入位置的索引。因为数组已排序,所以我们可以想到二分查找法,因为查找到的条件是找到第一个等于或者大于 `target` 的元素的位置,所以二分法略作变动即可。 43 | 44 | ```java 45 | class Solution { 46 | public int searchInsert(int[] nums, int target) { 47 | int left = 0, right = nums.length - 1, mid = (right + left) >> 1; 48 | while (left <= right) { 49 | if (target <= nums[mid]) right = mid - 1; 50 | else left = mid + 1; 51 | mid = (right + left) >> 1; 52 | } 53 | return left; 54 | } 55 | } 56 | ``` 57 | 58 | 59 | ## 结语 60 | 61 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 62 | 63 | 64 | 65 | [title]: https://leetcode.com/problems/search-insert-position 66 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 67 | -------------------------------------------------------------------------------- /note/0088/README.md: -------------------------------------------------------------------------------- 1 | # [Merge Sorted Array][title] 2 | 3 | ## Description 4 | 5 | Given two sorted integer arrays *nums1* and *nums2*, merge *nums2* into *nums1* as one sorted array. 6 | 7 | **Note:** 8 | 9 | - The number of elements initialized in *nums1* and *nums2* are *m* and *n* respectively. 10 | - You may assume that *nums1* has enough space (size that is greater or equal to *m* + *n*) to hold additional elements from *nums2*. 11 | 12 | **Example:** 13 | 14 | ``` 15 | Input: 16 | nums1 = [1,2,3,0,0,0], m = 3 17 | nums2 = [2,5,6], n = 3 18 | 19 | Output: [1,2,2,3,5,6] 20 | ``` 21 | 22 | **Tags:** Array, Two Pointers 23 | 24 | 25 | ## 思路 26 | 27 | 题意是给两个已排序的数组 `nums1` 和 `nums2`,合并 `nums2` 到 `nums1` 中,两数组元素个数分别为 `m` 和 `n`,而且 `nums1` 数组的长度足够容纳 `m + n` 个元素,如果我们按顺序排下去,那肯定要开辟一个新数组来保存元素,如果我们选择逆序,这样利用 `nums1` 自身空间足矣,不会出现覆盖的情况,依次把大的元素插入到 `nums1` 的末尾,确保 `nums2` 中的元素全部插入到 `nums1` 即可。 28 | 29 | ```java 30 | class Solution { 31 | public void merge(int[] nums1, int m, int[] nums2, int n) { 32 | int p = m-- + n-- - 1; 33 | while (m >= 0 && n >= 0) 34 | nums1[p--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; 35 | while (n >= 0) 36 | nums1[p--] = nums2[n--]; 37 | } 38 | } 39 | ``` 40 | 41 | 42 | ## 结语 43 | 44 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 45 | 46 | 47 | 48 | [title]: https://leetcode.com/problems/merge-sorted-array 49 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 50 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0049/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._049; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | /** 11 | *
12 | * author: Blankj 13 | * blog : http://blankj.com 14 | * time : 2017/10/18 15 | * desc : 16 | *17 | */ 18 | public class Solution { 19 | public List
11 | * author: Blankj 12 | * blog : http://blankj.com 13 | * time : 2017/10/13 14 | * desc : 15 | *16 | */ 17 | public class Solution { 18 | public int leastBricks(List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/18 8 | * desc : 9 | *10 | */ 11 | public class ListNode { 12 | 13 | public int val; 14 | public ListNode next; 15 | 16 | public ListNode(int x) { 17 | val = x; 18 | } 19 | 20 | /** 21 | * 创建测试数据 22 | * 23 | * @param data [XX,XX,XX] 24 | * @return {@link ListNode} 25 | */ 26 | public static ListNode createTestData(String data) { 27 | if (data.equals("[]")) return null; 28 | data = data.substring(1, data.length() - 1); 29 | String[] split = data.split(","); 30 | int len = split.length; 31 | ListNode[] listNode = new ListNode[len + 1]; 32 | listNode[0] = new ListNode(Integer.valueOf(split[0])); 33 | for (int i = 1; i < len; i++) { 34 | listNode[i] = new ListNode(Integer.valueOf(split[i])); 35 | listNode[i - 1].next = listNode[i]; 36 | } 37 | return listNode[0]; 38 | } 39 | 40 | public static void print(ListNode listNode) { 41 | if (listNode == null) { 42 | System.out.println("null"); 43 | return; 44 | } 45 | StringBuilder str = new StringBuilder("[" + String.valueOf(listNode.val)); 46 | ListNode p = listNode.next; 47 | while (p != null) { 48 | str.append(",").append(String.valueOf(p.val)); 49 | p = p.next; 50 | } 51 | System.out.println(str.append("]")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /note/0003/README.md: -------------------------------------------------------------------------------- 1 | # [Longest Substring Without Repeating Characters][title] 2 | 3 | ## Description 4 | 5 | Given a string, find the length of the **longest substring** without repeating characters. 6 | 7 | **Examples:** 8 | 9 | Given `"abcabcbb"`, the answer is `"abc"`, which the length is 3. 10 | 11 | Given `"bbbbb"`, the answer is `"b"`, with the length of 1. 12 | 13 | Given `"pwwkew"`, the answer is `"wke"`, with the length of 3. Note that the answer must be a **substring**, `"pwke"` is a *subsequence* and not a substring. 14 | 15 | **Tags:** Hash Table, Two Pointers, String 16 | 17 | 18 | ## 思路 19 | 20 | 题意是计算不带重复字符的最长子字符串的长度,开辟一个 hash 数组来存储该字符上次出现的位置,比如 `hash[a] = 3` 就是代表 `a` 字符前一次出现的索引在 3,遍历该字符串,获取到上次出现的最大索引(只能向前,不能退后),与当前的索引做差获取的就是本次所需长度,从中迭代出最大值就是最终答案。 21 | 22 | ```java 23 | class Solution { 24 | public int lengthOfLongestSubstring(String s) { 25 | int len; 26 | if (s == null || (len = s.length()) == 0) return 0; 27 | int preP = 0, max = 0; 28 | int[] hash = new int[128]; 29 | for (int i = 0; i < len; ++i) { 30 | char c = s.charAt(i); 31 | if (hash[c] > preP) { 32 | preP = hash[c]; 33 | } 34 | int l = i - preP + 1; 35 | hash[c] = i + 1; 36 | if (l > max) max = l; 37 | } 38 | return max; 39 | } 40 | } 41 | ``` 42 | 43 | 44 | ## 结语 45 | 46 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 47 | 48 | 49 | 50 | [title]: https://leetcode.com/problems/longest-substring-without-repeating-characters 51 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 52 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0056/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._056; 2 | 3 | import com.blankj.structure.Interval; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Comparator; 7 | import java.util.List; 8 | 9 | /** 10 | *
11 | * author: Blankj 12 | * blog : http://blankj.com 13 | * time : 2017/10/19 14 | * desc : 15 | *16 | */ 17 | public class Solution { 18 | public List
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2017/10/10 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | // public int minDepth(TreeNode root) { 18 | // if (root == null) return 0; 19 | // int l = minDepth(root.left); 20 | // int r = minDepth(root.right); 21 | // if (l != 0 && r != 0) return 1 + Math.min(l, r); 22 | // return l + r + 1; 23 | // } 24 | 25 | public int minDepth(TreeNode root) { 26 | if (root == null) return 0; 27 | LinkedList
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/04 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | // public int maxSubArray(int[] nums) { 13 | // int len = nums.length, dp = nums[0], max = dp; 14 | // for (int i = 1; i < len; ++i) { 15 | // dp = nums[i] + (dp > 0 ? dp : 0); 16 | // if (dp > max) max = dp; 17 | // } 18 | // return max; 19 | // } 20 | public int maxSubArray(int[] nums) { 21 | return helper(nums, 0, nums.length - 1); 22 | } 23 | 24 | private int helper(int[] nums, int left, int right) { 25 | if (left >= right) return nums[left]; 26 | int mid = (left + right) >> 1; 27 | int leftAns = helper(nums, left, mid); 28 | int rightAns = helper(nums, mid + 1, right); 29 | int leftMax = nums[mid], rightMax = nums[mid + 1]; 30 | int temp = 0; 31 | for (int i = mid; i >= left; --i) { 32 | temp += nums[i]; 33 | if (temp > leftMax) leftMax = temp; 34 | } 35 | temp = 0; 36 | for (int i = mid + 1; i <= right; ++i) { 37 | temp += nums[i]; 38 | if (temp > rightMax) rightMax = temp; 39 | } 40 | return Math.max(Math.max(leftAns, rightAns), leftMax + rightMax); 41 | } 42 | 43 | public static void main(String[] args) { 44 | Solution solution = new Solution(); 45 | int[] nums0 = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}; 46 | System.out.println(solution.maxSubArray(nums0)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /note/0121/README.md: -------------------------------------------------------------------------------- 1 | # [Best Time to Buy and Sell Stock][title] 2 | 3 | ## Description 4 | 5 | Say you have an array for which the *i*th element is the price of a given stock on day *i*. 6 | 7 | If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 8 | 9 | Note that you cannot sell a stock before you buy one. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: [7,1,5,3,6,4] 15 | Output: 5 16 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 17 | Not 7-1 = 6, as selling price needs to be larger than buying price. 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: [7,6,4,3,1] 24 | Output: 0 25 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 26 | ``` 27 | 28 | **Tags:** Array, Dynamic Programmin 29 | 30 | 31 | ## 思路 32 | 33 | 题意是给出一个数组代表每天的股票金额,让你在最多买卖一次的情况下算出最大的收益额,最简单的就是模拟即可,每次记录当前值减去最小值的差值,与上一次的进行比较然后更新最大值即可。 34 | 35 | ```java 36 | class Solution { 37 | public int maxProfit(int[] prices) { 38 | int max = 0, minPrice = Integer.MAX_VALUE; 39 | for (int i = 0; i < prices.length; ++i) { 40 | if (prices[i] < minPrice) minPrice = prices[i]; 41 | int delta = prices[i] - minPrice; 42 | if (delta > max) max = delta; 43 | } 44 | return max; 45 | } 46 | } 47 | ``` 48 | 49 | 50 | ## 结语 51 | 52 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 53 | 54 | 55 | 56 | [title]: https://leetcode.com/problems/best-time-to-buy-and-sell-stock 57 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 58 | -------------------------------------------------------------------------------- /src/com/blankj/structure/Interval.java: -------------------------------------------------------------------------------- 1 | package com.blankj.structure; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/10/19 11 | * desc : 12 | *13 | */ 14 | public class Interval { 15 | public int start; 16 | public int end; 17 | 18 | public Interval() { 19 | start = 0; 20 | end = 0; 21 | } 22 | 23 | public Interval(int s, int e) { 24 | start = s; 25 | end = e; 26 | } 27 | 28 | /** 29 | * 创建测试数据 30 | * 31 | * @param data [[X,X],[X,X],[X,X]] 32 | * @return {@link List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/12 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 13 | int len = nums1.length + nums2.length; 14 | if (len % 2 == 0) { 15 | return (helper(nums1, 0, nums2, 0, len / 2) + helper(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0; 16 | } 17 | return helper(nums1, 0, nums2, 0, (len + 1) / 2); 18 | } 19 | 20 | private int helper(int[] nums1, int m, int[] nums2, int n, int k) { 21 | if (m >= nums1.length) return nums2[n + k - 1]; 22 | if (n >= nums2.length) return nums1[m + k - 1]; 23 | if (k == 1) return Math.min(nums1[m], nums2[n]); 24 | 25 | int p1 = m + k / 2 - 1; 26 | int p2 = n + k / 2 - 1; 27 | int mid1 = p1 < nums1.length ? nums1[p1] : Integer.MAX_VALUE; 28 | int mid2 = p2 < nums2.length ? nums2[p2] : Integer.MAX_VALUE; 29 | if (mid1 < mid2) { 30 | return helper(nums1, m + k / 2, nums2, n, k - k / 2); 31 | } 32 | return helper(nums1, m, nums2, n + k / 2, k - k / 2); 33 | } 34 | 35 | public static void main(String[] args) { 36 | Solution solution = new Solution(); 37 | System.out.println(solution.findMedianSortedArrays( 38 | new int[]{1, 3}, 39 | new int[]{2} 40 | )); 41 | System.out.println(solution.findMedianSortedArrays( 42 | new int[]{1, 2}, 43 | new int[]{3, 4} 44 | )); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0015/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._015; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | /** 8 | *
9 | * author: Blankj 10 | * blog : http://blankj.com 11 | * time : 2017/10/14 12 | * desc : 13 | *14 | */ 15 | public class Solution { 16 | public List
11 | * author: Blankj 12 | * blog : http://blankj.com 13 | * time : 2017/10/24 14 | * desc : 15 | *16 | */ 17 | public class Solution { 18 | public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/04/23 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public int myAtoi(String str) { 13 | int i = 0, ans = 0, sign = 1, len = str.length(); 14 | while (i < len && str.charAt(i) == ' ') ++i; 15 | if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) { 16 | sign = str.charAt(i++) == '+' ? 1 : -1; 17 | } 18 | for (; i < len; ++i) { 19 | int tmp = str.charAt(i) - '0'; 20 | if (tmp < 0 || tmp > 9) break; 21 | if (ans > Integer.MAX_VALUE / 10 22 | || (ans == Integer.MAX_VALUE / 10 && (sign == 1 && tmp > 7 || sign == -1 && tmp > 8))) { 23 | return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; 24 | } else { 25 | ans = ans * 10 + tmp; 26 | } 27 | } 28 | return sign * ans; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Solution solution = new Solution(); 33 | System.out.println(solution.myAtoi(" +1")); 34 | System.out.println(solution.myAtoi(" -1")); 35 | System.out.println(solution.myAtoi("")); 36 | System.out.println(solution.myAtoi("a1")); 37 | System.out.println(solution.myAtoi("100000000000000000000")); 38 | System.out.println(solution.myAtoi("-100000000000000000000")); 39 | System.out.println(solution.myAtoi("-3924x8fc")); 40 | System.out.println(solution.myAtoi(String.valueOf(Integer.MIN_VALUE))); 41 | System.out.println(solution.myAtoi(String.valueOf(Integer.MAX_VALUE))); 42 | } 43 | } -------------------------------------------------------------------------------- /note/0028/README.md: -------------------------------------------------------------------------------- 1 | # [Implement strStr()][title] 2 | 3 | ## Description 4 | 5 | Implement [strStr()](http://www.cplusplus.com/reference/cstring/strstr/). 6 | 7 | Return the index of the first occurrence of needle in haystack, or **-1** if needle is not part of haystack. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: haystack = "hello", needle = "ll" 13 | Output: 2 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: haystack = "aaaaa", needle = "bba" 20 | Output: -1 21 | ``` 22 | 23 | **Clarification:** 24 | 25 | What should we return when `needle` is an empty string? This is a great question to ask during an interview. 26 | 27 | For the purpose of this problem, we will return 0 when `needle` is an empty string. This is consistent to C's [strstr()](http://www.cplusplus.com/reference/cstring/strstr/) and Java's [indexOf()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)). 28 | 29 | Tags:** Two Pointers, String 30 | 31 | 32 | ## 思路 33 | 34 | 题意是从主串中找到子串的索引,如果找不到则返回-1,当子串长度大于主串,直接返回-1,然后我们只需要遍历比较即可。 35 | 36 | ```java 37 | class Solution { 38 | public int strStr(String haystack, String needle) { 39 | int l1 = haystack.length(), l2 = needle.length(); 40 | if (l1 < l2) return -1; 41 | for (int i = 0; ; i++) { 42 | if (i + l2 > l1) return -1; 43 | for (int j = 0; ; j++) { 44 | if (j == l2) return i; 45 | if (haystack.charAt(i + j) != needle.charAt(j)) break; 46 | } 47 | } 48 | } 49 | } 50 | ``` 51 | 52 | 53 | ## 结语 54 | 55 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 56 | 57 | 58 | 59 | [title]: https://leetcode.com/problems/implement-strstr 60 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 61 | -------------------------------------------------------------------------------- /note/0100/README.md: -------------------------------------------------------------------------------- 1 | # [Same Tree][title] 2 | 3 | ## Description 4 | 5 | Given two binary trees, write a function to check if they are the same or not. 6 | 7 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: 1 1 13 | / \ / \ 14 | 2 3 2 3 15 | 16 | [1,2,3], [1,2,3] 17 | 18 | Output: true 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: 1 1 25 | / \ 26 | 2 2 27 | 28 | [1,2], [1,null,2] 29 | 30 | Output: false 31 | ``` 32 | 33 | **Example 3:** 34 | 35 | ``` 36 | Input: 1 1 37 | / \ / \ 38 | 2 1 1 2 39 | 40 | [1,2,1], [1,1,2] 41 | 42 | Output: false 43 | ``` 44 | 45 | **Tags:** Tree, Depth-first Search 46 | 47 | 48 | ## 思路 49 | 50 | 题意是比较两棵二叉树是否相同,那么我们就深搜比较各个节点即可。 51 | 52 | ```java 53 | /** 54 | * Definition for a binary tree node. 55 | * public class TreeNode { 56 | * int val; 57 | * TreeNode left; 58 | * TreeNode right; 59 | * TreeNode(int x) { val = x; } 60 | * } 61 | */ 62 | class Solution { 63 | public boolean isSameTree(TreeNode p, TreeNode q) { 64 | if (p == null && q == null) return true; 65 | if (p == null || q == null) return false; 66 | if (p.val == q.val) { 67 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 68 | } 69 | return false; 70 | } 71 | } 72 | ``` 73 | 74 | 75 | ## 结语 76 | 77 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 78 | 79 | 80 | 81 | [title]: https://leetcode.com/problems/same-tree 82 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 83 | -------------------------------------------------------------------------------- /note/0019/README.md: -------------------------------------------------------------------------------- 1 | # [Remove Nth Node From End of List][title] 2 | 3 | ## Description 4 | 5 | Given a linked list, remove the *n*-th node from the end of list and return its head. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Given linked list: 1->2->3->4->5, and n = 2. 11 | 12 | After removing the second node from the end, the linked list becomes 1->2->3->5. 13 | ``` 14 | 15 | **Note:** 16 | 17 | Given *n* will always be valid. 18 | 19 | **Follow up:** 20 | 21 | Could you do this in one pass? 22 | 23 | **Tags:** Linked List, Two Pointers 24 | 25 | 26 | ## 思路 27 | 28 | 题意是让你删除链表中的倒数第 n 个数,我的解法是利用双指针,这两个指针相差 n 个元素,当后面的指针扫到链表末尾的时候,自然它前面的那个指针所指向的下一个元素就是要删除的元素,即 `pre.next = pre.next.next;`,但是如果一开始后面的指针指向的为空,此时代表的意思就是要删除第一个元素,即 `head = head.next;`。 29 | 30 | ```java 31 | /** 32 | * Definition for singly-linked list. 33 | * public class ListNode { 34 | * int val; 35 | * ListNode next; 36 | * ListNode(int x) { val = x; } 37 | * } 38 | */ 39 | class Solution { 40 | public ListNode removeNthFromEnd(ListNode head, int n) { 41 | ListNode pre = head; 42 | ListNode afterPreN = head; 43 | while (n-- != 0) { 44 | afterPreN = afterPreN.next; 45 | } 46 | if (afterPreN != null) { 47 | while (afterPreN.next != null) { 48 | pre = pre.next; 49 | afterPreN = afterPreN.next; 50 | } 51 | pre.next = pre.next.next; 52 | } else { 53 | head = head.next; 54 | } 55 | return head; 56 | } 57 | } 58 | ``` 59 | 60 | 61 | ## 结语 62 | 63 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 64 | 65 | 66 | 67 | [title]: https://leetcode.com/problems/remove-nth-node-from-end-of-list 68 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 69 | -------------------------------------------------------------------------------- /src/com/blankj/easy/_0067/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.easy._067; 2 | 3 | /** 4 | *
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/05/07 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | public String addBinary(String a, String b) { 13 | StringBuilder sb = new StringBuilder(); 14 | int carry = 0, p1 = a.length() - 1, p2 = b.length() - 1; 15 | while (p1 >= 0 && p2 >= 0) { 16 | carry += a.charAt(p1--) - '0'; 17 | carry += b.charAt(p2--) - '0'; 18 | sb.insert(0, (char) (carry % 2 + '0')); 19 | carry >>= 1; 20 | } 21 | while (p1 >= 0) { 22 | carry += a.charAt(p1--) - '0'; 23 | sb.insert(0, (char) (carry % 2 + '0')); 24 | carry >>= 1; 25 | } 26 | while (p2 >= 0) { 27 | carry += b.charAt(p2--) - '0'; 28 | sb.insert(0, (char) (carry % 2 + '0')); 29 | carry >>= 1; 30 | } 31 | if (carry == 1) { 32 | sb.insert(0, '1'); 33 | } 34 | return sb.toString(); 35 | } 36 | 37 | // public String addBinary(String a, String b) { 38 | // StringBuilder sb = new StringBuilder(); 39 | // int carry = 0, p1 = a.length() - 1, p2 = b.length() - 1; 40 | // while (p1 >= 0 || p2 >= 0 || carry == 1) { 41 | // carry += p1 >= 0 ? a.charAt(p1--) - '0' : 0; 42 | // carry += p2 >= 0 ? b.charAt(p2--) - '0' : 0; 43 | // sb.insert(0, (char) (carry % 2 + '0')); 44 | // carry >>= 1; 45 | // } 46 | // return sb.print(); 47 | // } 48 | 49 | public static void main(String[] args) { 50 | Solution solution = new Solution(); 51 | System.out.println(solution.addBinary("11", "1")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /note/0002/README.md: -------------------------------------------------------------------------------- 1 | # [Add Two Numbers][title] 2 | 3 | ## Description 4 | 5 | You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order** and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 6 | 7 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 8 | 9 | **Example** 10 | 11 | ``` 12 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 13 | Output: 7 -> 0 -> 8 14 | Explanation: 342 + 465 = 807. 15 | ``` 16 | 17 | **Tags:** Linked List, Math 18 | 19 | 20 | ## 思路 21 | 22 | 题意我也是看了好久才看懂,就是以链表表示一个数,低位在前,高位在后,所以题中的例子就是 `342 + 465 = 807`,所以我们模拟计算即可。 23 | 24 | ```java 25 | /** 26 | * Definition for singly-linked list. 27 | * public class ListNode { 28 | * int val; 29 | * ListNode next; 30 | * ListNode(int x) { val = x; } 31 | * } 32 | */ 33 | class Solution { 34 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 35 | ListNode node = new ListNode(0); 36 | ListNode n1 = l1, n2 = l2, t = node; 37 | int sum = 0; 38 | while (n1 != null || n2 != null) { 39 | sum /= 10; 40 | if (n1 != null) { 41 | sum += n1.val; 42 | n1 = n1.next; 43 | } 44 | if (n2 != null) { 45 | sum += n2.val; 46 | n2 = n2.next; 47 | } 48 | t.next = new ListNode(sum % 10); 49 | t = t.next; 50 | } 51 | if (sum / 10 != 0) t.next = new ListNode(1); 52 | return node.next; 53 | } 54 | } 55 | ``` 56 | 57 | 58 | ## 结语 59 | 60 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 61 | 62 | 63 | 64 | [title]: https://leetcode.com/problems/add-two-numbers 65 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 66 | -------------------------------------------------------------------------------- /src/com/blankj/medium/_0022/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.medium._022; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | 8 | /** 9 | *
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2018/01/30 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | // public List
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2017/10/09 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | // public boolean isSymmetric(TreeNode root) { 18 | // return root == null || helper(root.left, root.right); 19 | // } 20 | // 21 | // private boolean helper(TreeNode left, TreeNode right) { 22 | // if (left == null || right == null) return left == right; 23 | // if (left.val != right.val) return false; 24 | // return helper(left.left, right.right) && helper(left.right, right.left); 25 | // } 26 | 27 | public boolean isSymmetric(TreeNode root) { 28 | if (root == null) return true; 29 | LinkedList
9 | * author: Blankj 10 | * blog : http://blankj.com 11 | * time : 2017/10/15 12 | * desc : 13 | *14 | */ 15 | public class Solution { 16 | // private static String[] map = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 17 | // 18 | // public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/12/11 8 | * desc : 9 | *10 | */ 11 | class Solution { 12 | 13 | // public String convert(String s, int numRows) { 14 | // if (numRows <= 1) return s; 15 | // int len = s.length(); 16 | // char[] chars = s.toCharArray(); 17 | // int cycle = 2 * (numRows - 1); 18 | // StringBuilder sb = new StringBuilder(); 19 | // for (int j = 0; j < len; j += cycle) { 20 | // sb.append(chars[j]); 21 | // } 22 | // for (int i = 1; i < numRows - 1; i++) { 23 | // int step = 2 * i; 24 | // for (int j = i; j < len; j += step) { 25 | // sb.append(chars[j]); 26 | // step = cycle - step; 27 | // } 28 | // } 29 | // for (int j = numRows - 1; j < len; j += cycle) { 30 | // sb.append(chars[j]); 31 | // } 32 | // return sb.toString(); 33 | // } 34 | 35 | public String convert(String s, int numRows) { 36 | if (numRows <= 1) return s; 37 | int len = s.length(); 38 | char[] chars = s.toCharArray(); 39 | StringBuilder[] sbs = new StringBuilder[numRows]; 40 | for (int i = 0; i < numRows; i++) { 41 | sbs[i] = new StringBuilder(); 42 | } 43 | int i = 0; 44 | while (i < len) { 45 | for (int j = 0; j < numRows && i < len; ++j) { 46 | sbs[j].append(chars[i++]); 47 | } 48 | for (int j = numRows - 2; j >= 1 && i < len; --j) { 49 | sbs[j].append(chars[i++]); 50 | } 51 | } 52 | for (i = 1; i < numRows; i++) { 53 | sbs[0].append(sbs[i]); 54 | } 55 | return sbs[0].toString(); 56 | } 57 | 58 | public static void main(String[] args) { 59 | Solution solution = new Solution(); 60 | System.out.println(solution.convert("PAYPALISHIRING", 3));// PAHNAPLSIIGYIR 61 | System.out.println(solution.convert("ABCD", 4)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /note/0043/README.md: -------------------------------------------------------------------------------- 1 | # [Multiply Strings][title] 2 | 3 | ## Description 4 | 5 | 1. Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: num1 = "2", num2 = "3" 11 | Output: "6" 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: num1 = "123", num2 = "456" 18 | Output: "56088" 19 | ``` 20 | 21 | **Note:** 22 | 23 | 1. The length of both `num1` and `num2` is < 110. 24 | 2. Both `num1` and `num2` contain only digits `0-9`. 25 | 3. Both `num1` and `num2` do not contain any leading zero, except the number 0 itself. 26 | 4. You **must not use any built-in BigInteger library** or **convert the inputs to integer** directly. 27 | 28 | **Tags:** Math, String 29 | 30 | 31 | ## 思路 32 | 33 | 题意是让你计算两个非负字符串的乘积,我们模拟小学数学的方式来做,一位一位模拟计算,再各位累加。 34 | 35 | ```java 36 | class Solution { 37 | public String multiply(String num1, String num2) { 38 | if (num1.equals("0") || num2.equals("0")) return "0"; 39 | int l1 = num1.length(), l2 = num2.length(), l = l1 + l2; 40 | char[] ans = new char[l]; 41 | char[] c1 = num1.toCharArray(); 42 | char[] c2 = num2.toCharArray(); 43 | for (int i = l1 - 1; i >= 0; --i) { 44 | int c = c1[i] - '0'; 45 | for (int j = l2 - 1; j >= 0; --j) { 46 | ans[i + j + 1] += c * (c2[j] - '0'); 47 | } 48 | } 49 | for (int i = l - 1; i > 0; --i) { 50 | if (ans[i] > 9) { 51 | ans[i - 1] += ans[i] / 10; 52 | ans[i] %= 10; 53 | } 54 | } 55 | StringBuilder sb = new StringBuilder(); 56 | int i = 0; 57 | for (; ; ++i) if (ans[i] != 0) break; 58 | for (; i < ans.length; ++i) sb.append((char) (ans[i] + '0')); 59 | return sb.toString(); 60 | } 61 | } 62 | ``` 63 | 64 | 65 | ## 结语 66 | 67 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 68 | 69 | 70 | 71 | [title]: https://leetcode.com/problems/multiply-strings 72 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 73 | -------------------------------------------------------------------------------- /note/0024/README.md: -------------------------------------------------------------------------------- 1 | # [Swap Nodes in Pairs][title] 2 | 3 | ## Description 4 | 5 | Given a linked list, swap every two adjacent nodes and return its head. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Given 1->2->3->4, you should return the list as 2->1->4->3. 11 | ``` 12 | 13 | **Note:** 14 | 15 | - Your algorithm should use only constant extra space. 16 | - You may **not** modify the values in the list's nodes, only nodes itself may be changed. 17 | 18 | **Tags:** Linked List 19 | 20 | 21 | ## 思路 0 22 | 23 | 题意是让你交换链表中相邻的两个节点,最终返回交换后链表的头,限定你空间复杂度为 O(1)。我们可以用递归来算出子集合的结果,递归的终点就是指针指到链表末少于两个元素时,如果不是终点,那么我们就对其两节点进行交换,这里我们需要一个临时节点来作为交换桥梁,就不多说了。 24 | 25 | ```java 26 | /** 27 | * Definition for singly-linked list. 28 | * public class ListNode { 29 | * int val; 30 | * ListNode next; 31 | * ListNode(int x) { val = x; } 32 | * } 33 | */ 34 | class Solution { 35 | public ListNode swapPairs(ListNode head) { 36 | if (head == null || head.next == null) return head; 37 | ListNode node = head.next; 38 | head.next = swapPairs(node.next); 39 | node.next = head; 40 | return node; 41 | } 42 | } 43 | ``` 44 | 45 | 46 | ## 思路 1 47 | 48 | 另一种实现方式就是用循环来实现了,两两交换节点,也需要一个临时节点来作为交换桥梁,直到当前指针指到链表末少于两个元素时停止,代码很简单,如下所示。 49 | 50 | ```java 51 | /** 52 | * Definition for singly-linked list. 53 | * public class ListNode { 54 | * int val; 55 | * ListNode next; 56 | * ListNode(int x) { val = x; } 57 | * } 58 | */ 59 | class Solution { 60 | public ListNode swapPairs(ListNode head) { 61 | ListNode preHead = new ListNode(0), cur = preHead; 62 | preHead.next = head; 63 | while (cur.next != null && cur.next.next != null) { 64 | ListNode temp = cur.next.next; 65 | cur.next.next = temp.next; 66 | temp.next = cur.next; 67 | cur.next = temp; 68 | cur = cur.next.next; 69 | } 70 | return preHead.next; 71 | } 72 | } 73 | ``` 74 | 75 | 76 | ## 结语 77 | 78 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 79 | 80 | 81 | 82 | [title]: https://leetcode.com/problems/swap-nodes-in-pairs 83 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 84 | -------------------------------------------------------------------------------- /note/0063/README.md: -------------------------------------------------------------------------------- 1 | # [不同路径 II(Unique Paths II)][title] 2 | 3 | ## 题目描述 4 | 5 | 一个机器人位于一个 _m x n_ 网格的左上角 (起始点在下图中标记为“Start” )。 6 | 7 | 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 8 | 9 | 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径? 10 | 11 |  12 | 13 | 网格中的障碍物和空位置分别用 `1` 和 `0` 来表示。 14 | 15 | **说明:**_m_ 和 _n_ 的值均不超过 100。 16 | 17 | **示例 1:** 18 | ``` 19 | 输入: 20 | [ 21 | [0,0,0], 22 | [0,1,0], 23 | [0,0,0] 24 | ] 25 | 输出: 2 26 | 解释: 27 | 3x3 网格的正中间有一个障碍物。 28 | 从左上角到右下角一共有 2 条不同的路径: 29 | 1. 向右 -> 向右 -> 向下 -> 向下 30 | 2. 向下 -> 向下 -> 向右 -> 向右 31 | ``` 32 | 33 | **标签:** 数组、动态规划 34 | 35 | 36 | ## 思路 37 | 38 | 做过爬楼梯的应该很快就能想到这是一道很典型的动态规划题目, 39 | 40 | 我们令 `dp[i][j]` 表示走到格子 `(i, j)` 的路径数, 41 | 42 | 那么当 `(i, j)` 没障碍物时,`dp[i][j] = 0`; 43 | 44 | 那么当 `(i, j)` 有障碍物时,`dp[i][j] = dp[i - 1][j] + dp[i][j - 1]`; 45 | 46 | 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法,因此初始化 `dp[i][0]`(`dp[0][j]`)值为 1,且遇到障碍物时后面值都为 0; 47 | 48 | 有了这些条件,我相信你肯定可以写出代码来了,具体如下所示: 49 | 50 | 51 | ```java 52 | class Solution { 53 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 54 | int m = obstacleGrid.length, n = obstacleGrid[0].length; 55 | int[][] dp = new int[m][n]; 56 | // 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法, 57 | // 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0; 58 | for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) { 59 | dp[i][0] = 1; 60 | } 61 | for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) { 62 | dp[0][j] = 1; 63 | } 64 | 65 | for (int i = 1; i < m; i++) { 66 | for (int j = 1; j < n; j++) { 67 | if (obstacleGrid[i][j] == 0) { 68 | // 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 69 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 70 | } 71 | } 72 | } 73 | return dp[m - 1][n - 1]; 74 | } 75 | } 76 | ``` 77 | 78 | 79 | ## 结语 80 | 81 | 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] 82 | 83 | 84 | 85 | [title]: https://leetcode-cn.com/problems/unique-paths-ii 86 | [ajl]: https://github.com/Blankj/awesome-java-leetcode 87 | -------------------------------------------------------------------------------- /note/0056/README.md: -------------------------------------------------------------------------------- 1 | # [Merge Intervals][title] 2 | 3 | ## Description 4 | 5 | Given a collection of intervals, merge all overlapping intervals. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: [[1,3],[2,6],[8,10],[15,18]] 11 | Output: [[1,6],[8,10],[15,18]] 12 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 13 | ``` 14 | 15 | **Example 2:** 16 | 17 | ``` 18 | Input: [[1,4],[4,5]] 19 | Output: [[1,5]] 20 | Explanation: Intervals [1,4] and [4,5] are considerred overlapping. 21 | ``` 22 | 23 | **Tags:** Array, Sort 24 | 25 | 26 | ## 思路 27 | 28 | 题意是给你一组区间,让你把区间合并成没有交集的一组区间。我们可以把区间按 `start` 进行排序,然后遍历排序后的区间,如果当前的 `start` 小于前者的 `end`,那么说明这两个存在交集,我们取两者中较大的 `end` 即可;否则的话直接插入到结果序列中即可。 29 | 30 | ```java 31 | /** 32 | * Definition for an interval. 33 | * public class Interval { 34 | * int start; 35 | * int end; 36 | * Interval() { start = 0; end = 0; } 37 | * Interval(int s, int e) { start = s; end = e; } 38 | * } 39 | */ 40 | class Solution { 41 | public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/11/04 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | // int st, end; 13 | // 14 | // public String longestPalindrome(String s) { 15 | //// st = 0; 16 | //// end = 0; 17 | // int len = s.length(); 18 | // if (len <= 1) return s; 19 | // char[] chars = s.toCharArray(); 20 | // for (int i = 0; i < len; i++) { 21 | // helper(chars, i, i); 22 | // helper(chars, i, i + 1); 23 | // } 24 | // return s.substring(st, end + 1); 25 | // } 26 | // 27 | // private void helper(char[] chars, int l, int r) { 28 | // while (l >= 0 && r < chars.length && chars[l] == chars[r]) { 29 | // --l; 30 | // ++r; 31 | // } 32 | // if (end - st < r - l - 2) { 33 | // st = l + 1; 34 | // end = r - 1; 35 | // } 36 | // } 37 | 38 | // public String longestPalindrome(String s) { 39 | // int len = s.length(); 40 | // if (len <= 1) return s; 41 | // int st = 0, end = 0; 42 | // char[] chars = s.toCharArray(); 43 | // boolean[][] dp = new boolean[len][len]; 44 | // for (int i = 0; i < len; i++) { 45 | // dp[i][i] = true; 46 | // for (int j = 0; j < i; j++) { 47 | // if (j + 1 == i) { 48 | // dp[j][i] = chars[j] == chars[i]; 49 | // } else { 50 | // dp[j][i] = dp[j + 1][i - 1] && chars[j] == chars[i]; 51 | // } 52 | // if (dp[j][i] && i - j > end - st) { 53 | // st = j; 54 | // end = i; 55 | // } 56 | // } 57 | // } 58 | // return s.substring(st, end + 1); 59 | // } 60 | 61 | public String longestPalindrome(String s) { 62 | 63 | return s; 64 | } 65 | 66 | public static void main(String[] args) { 67 | Solution solution = new Solution(); 68 | System.out.println(solution.longestPalindrome("babad")); 69 | System.out.println(solution.longestPalindrome("cbbd")); 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/com/blankj/hard/_0068/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.hard._068; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | *
8 | * author: Blankj 9 | * blog : http://blankj.com 10 | * time : 2017/11/01 11 | * desc : 12 | *13 | */ 14 | public class Solution { 15 | 16 | public List
7 | * author: Blankj 8 | * blog : http://blankj.com 9 | * time : 2020/06/30 10 | * desc : 11 | *12 | */ 13 | public class Solution { 14 | // public int minSubArrayLen(int s, int[] nums) { 15 | // int ans = Integer.MAX_VALUE; 16 | // for (int i = 0; i < nums.length; i++) { 17 | // int sum = nums[i]; 18 | // if (sum >= s) { 19 | // return 1; 20 | // } 21 | // for (int j = i + 1; j < nums.length; j++) { 22 | // sum += nums[j]; 23 | // if (sum >= s) { 24 | // ans = Math.min(ans, j - i + 1); 25 | // break; 26 | // } 27 | // } 28 | // } 29 | // return ans == Integer.MAX_VALUE ? 0 : ans; 30 | // } 31 | 32 | // public int minSubArrayLen(int s, int[] nums) { 33 | // int left = 0, right = 0, sum = 0, ans = Integer.MAX_VALUE; 34 | // while (right < nums.length) { 35 | // sum += nums[right++]; // 向右扩大窗口 36 | // while (sum >= s) { // 如果不小于 s,则收缩窗口左边界 37 | // ans = Math.min(ans, right - left);// 更新结果 38 | // sum -= nums[left++]; // 向左缩小窗口 39 | // } 40 | // } 41 | // return ans == Integer.MAX_VALUE ? 0 : ans; 42 | // } 43 | 44 | public int minSubArrayLen(int s, int[] nums) { 45 | int ans = Integer.MAX_VALUE; 46 | int[] sums = new int[nums.length + 1]; 47 | for (int i = 0; i < nums.length; i++) { 48 | sums[i + 1] = sums[i] + nums[i]; 49 | } 50 | for (int i = 0; i < nums.length; i++) { 51 | int target = s + sums[i]; // 确定要搜索的目标值 52 | // Java 二分查找 Arrays.binarySearch 如果找到就会返回该元素的索引; 53 | // 如果没找到就会返回一个负数,这个负数取反之后再减一就是查找的值应该在数组中的位置; 54 | // 例如 [-1, 0, 1, 5] 中二分查找 2,其返回值就是 -4,其 -(-4) - 1 = 3,所以 2 这个元素插入到数组的索引就是 3 55 | int bound = Arrays.binarySearch(sums, target); 56 | if (bound < 0) { 57 | bound = -bound - 1; 58 | } 59 | if (bound < sums.length) { // 当 bound 确定插入点不在 sums 数组的最后面时,说明不小于 target 的值了 60 | ans = Math.min(ans, bound - i); 61 | } 62 | } 63 | return ans == Integer.MAX_VALUE ? 0 : ans; 64 | } 65 | 66 | public static void main(String[] args) { 67 | Solution solution = new Solution(); 68 | System.out.println(solution.minSubArrayLen(7, new int[]{2, 3, 1, 2, 4, 3})); 69 | } 70 | } -------------------------------------------------------------------------------- /src/com/blankj/hard/_0023/Solution.java: -------------------------------------------------------------------------------- 1 | package com.blankj.hard._023; 2 | 3 | import com.blankj.structure.ListNode; 4 | 5 | import java.util.Comparator; 6 | import java.util.PriorityQueue; 7 | 8 | /** 9 | *
10 | * author: Blankj 11 | * blog : http://blankj.com 12 | * time : 2017/10/15 13 | * desc : 14 | *15 | */ 16 | public class Solution { 17 | // public ListNode mergeKLists(ListNode[] lists) { 18 | // if (lists.length == 0) return null; 19 | // return helper(lists, 0, lists.length - 1); 20 | // } 21 | // 22 | // private ListNode helper(ListNode[] lists, int left, int right) { 23 | // if (left >= right) return lists[left]; 24 | // int mid = left + right >>> 1; 25 | // ListNode l0 = helper(lists, left, mid); 26 | // ListNode l1 = helper(lists, mid + 1, right); 27 | // return merge2Lists(l0, l1); 28 | // } 29 | // 30 | // private ListNode merge2Lists(ListNode l0, ListNode l1) { 31 | // ListNode node = new ListNode(0), tmp = node; 32 | // while (l0 != null && l1 != null) { 33 | // if (l0.val <= l1.val) { 34 | // tmp.next = new ListNode(l0.val); 35 | // l0 = l0.next; 36 | // } else { 37 | // tmp.next = new ListNode(l1.val); 38 | // l1 = l1.next; 39 | // } 40 | // tmp = tmp.next; 41 | // } 42 | // tmp.next = l0 != null ? l0 : l1; 43 | // return node.next; 44 | // } 45 | 46 | public ListNode mergeKLists(ListNode[] lists) { 47 | if (lists.length == 0) return null; 48 | PriorityQueue
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/06/05 8 | * desc : 9 | *10 | */ 11 | public class TreeNode { 12 | 13 | public int val; 14 | public TreeNode left; 15 | public TreeNode right; 16 | 17 | public TreeNode(int x) { 18 | val = x; 19 | } 20 | 21 | /** 22 | * 创建测试数据 23 | * 24 | * @param data [XX,XX,null,xx] 25 | * @return {@link TreeNode} 26 | */ 27 | public static TreeNode createTestData(String data) { 28 | if (data.equals("[]")) return null; 29 | data = data.substring(1, data.length() - 1); 30 | String[] split = data.split(","); 31 | int len = len = split.length; 32 | TreeNode[] treeNodes = new TreeNode[len]; 33 | data = data.substring(1, data.length() - 1); 34 | for (int i = 0; i < len; i++) { 35 | if (!split[i].equals("null")) { 36 | treeNodes[i] = new TreeNode(Integer.valueOf(split[i])); 37 | } 38 | } 39 | for (int i = 0; i < len; i++) { 40 | if (treeNodes[i] != null) { 41 | int leftIndex = i * 2 + 1; 42 | if (leftIndex < len) { 43 | treeNodes[i].left = treeNodes[leftIndex]; 44 | } 45 | int rightIndex = leftIndex + 1; 46 | if (rightIndex < len) { 47 | treeNodes[i].right = treeNodes[rightIndex]; 48 | } 49 | } 50 | } 51 | return treeNodes[0]; 52 | } 53 | 54 | private static final String space = " "; 55 | 56 | /** 57 | * 竖向打印二叉树 58 | * 59 | * @param root 二叉树根节点 60 | */ 61 | public static void print(TreeNode root) { 62 | print(root, 0); 63 | } 64 | 65 | private static void print(TreeNode node, int deep) { 66 | if (node == null) { 67 | printSpace(deep); 68 | System.out.println("#"); 69 | return; 70 | } 71 | print(node.right, deep + 1); 72 | printSpace(deep); 73 | printNode(node.val); 74 | print(node.left, deep + 1); 75 | } 76 | 77 | private static void printSpace(int count) { 78 | for (int i = 0; i < count; i++) { 79 | System.out.printf(space); 80 | } 81 | } 82 | 83 | private static void printNode(int val) { 84 | StringBuilder res = new StringBuilder(val + "<"); 85 | int spaceNum = space.length() - res.length(); 86 | for (int i = 0; i < spaceNum; i++) { 87 | res.append(" "); 88 | } 89 | System.out.println(res); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /note/0017/README.md: -------------------------------------------------------------------------------- 1 | # [Letter Combinations of a Phone Number][title] 2 | 3 | ## Description 4 | 5 | Given a digit string, return all possible letter combinations that the number could represent. 6 | 7 | A mapping of digit to letters (just like on the telephone buttons) is given below. 8 | 9 |  10 | 11 | **Example:** 12 | 13 | ``` 14 | Input: "23" 15 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 16 | ``` 17 | 18 | **Note:** 19 | 20 | Although the above answer is in lexicographical order, your answer could be in any order you want. 21 | 22 | **Tags:** String, Backtracking 23 | 24 | 25 | ## 思路 0 26 | 27 | 题意是给你按键,让你组合出所有不同结果,首先想到的肯定是回溯了,对每个按键的所有情况进行回溯,回溯的终点就是结果字符串长度和按键长度相同。 28 | 29 | ```java 30 | class Solution { 31 | private static String[] map = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 32 | 33 | public List
9 | * author: Blankj 10 | * blog : http://blankj.com 11 | * time : 2020/06/19 12 | * desc : 13 | *14 | */ 15 | public class Solution { 16 | // public TreeNode recoverFromPreorder(String S) { 17 | // char[] chars = S.toCharArray(); 18 | // int len = chars.length; 19 | // List
13 | * author: Blankj 14 | * blog : http://blankj.com 15 | * time : 2018/02/01 16 | * desc : 17 | *18 | */ 19 | public class Solution { 20 | public List
5 | * author: Blankj 6 | * blog : http://blankj.com 7 | * time : 2017/10/13 8 | * desc : 9 | *10 | */ 11 | public class Solution { 12 | // public boolean isMatch(String s, String p) { 13 | // if (p.isEmpty()) return s.isEmpty(); 14 | // if (p.length() == 1) { 15 | // return s.length() == 1 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'); 16 | // } 17 | // if (p.charAt(1) != '*') { 18 | // if (s.isEmpty()) return false; 19 | // return (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') 20 | // && isMatch(s.substring(1), p.substring(1)); 21 | // } 22 | // // match 1 or more preceding element 23 | // while (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) { 24 | // if (isMatch(s, p.substring(2))) return true; 25 | // s = s.substring(1); 26 | // } 27 | // // match 0 preceding element 28 | // return isMatch(s, p.substring(2)); 29 | // } 30 | // 31 | // public boolean isMatch(String s, String p) { 32 | // if (p.isEmpty()) return s.isEmpty(); 33 | // if (p.length() > 1 && p.charAt(1) == '*') { 34 | // return isMatch(s, p.substring(2)) 35 | // || (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') 36 | // && isMatch(s.substring(1), p)); 37 | // } 38 | // return !s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.') 39 | // && isMatch(s.substring(1), p.substring(1)); 40 | // } 41 | 42 | public boolean isMatch(String s, String p) { 43 | if (p.length() == 0) return s.length() == 0; 44 | int sL = s.length(), pL = p.length(); 45 | boolean[][] dp = new boolean[sL + 1][pL + 1]; 46 | char[] sc = s.toCharArray(), pc = p.toCharArray(); 47 | dp[0][0] = true; 48 | for (int i = 2; i <= pL; ++i) { 49 | if (pc[i - 1] == '*' && dp[0][i - 2]) { 50 | dp[0][i] = true; 51 | } 52 | } 53 | for (int i = 1; i <= sL; ++i) { 54 | for (int j = 1; j <= pL; ++j) { 55 | if (pc[j - 1] == '.' || pc[j - 1] == sc[i - 1]) { 56 | dp[i][j] = dp[i - 1][j - 1]; 57 | } 58 | if (pc[j - 1] == '*') { 59 | if (pc[j - 2] == sc[i - 1] || pc[j - 2] == '.') { 60 | dp[i][j] = dp[i - 1][j] || dp[i][j - 2]; 61 | } else { 62 | dp[i][j] = dp[i][j - 2]; 63 | } 64 | } 65 | } 66 | } 67 | return dp[sL][pL]; 68 | } 69 | 70 | public static void main(String[] args) { 71 | Solution solution = new Solution(); 72 | System.out.println(solution.isMatch("aa", "a")); // false 73 | System.out.println(solution.isMatch("aa", "aa")); // true 74 | System.out.println(solution.isMatch("aaa", "aa")); // false 75 | System.out.println(solution.isMatch("aa", "a*")); // true 76 | System.out.println(solution.isMatch("aa", ".*")); // true 77 | System.out.println(solution.isMatch("ab", ".*")); // true 78 | System.out.println(solution.isMatch("aab", "c*a*b"));// true 79 | } 80 | } 81 | --------------------------------------------------------------------------------