├── .gitignore
├── .project
├── LICENSE.txt
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── pengyifan
│ │ └── leetcode
│ │ ├── AddBinary.java
│ │ ├── AddDigits.java
│ │ ├── AddTwoNumbers.java
│ │ ├── ArrayBalancePoint.java
│ │ ├── BalancedBinaryTree.java
│ │ ├── BestTimeToBuyAndSellStock.java
│ │ ├── BestTimeToBuyAndSellStockII.java
│ │ ├── BinaryTreeInorderTraversal.java
│ │ ├── BinaryTreeLevelOrderTraversal.java
│ │ ├── BinaryTreeLevelOrderTraversalII.java
│ │ ├── BinaryTreePaths.java
│ │ ├── BinaryTreePostorderTraversal.java
│ │ ├── BinaryTreePreorderTraversal.java
│ │ ├── BulbSwitcher.java
│ │ ├── BullsAndCows.java
│ │ ├── Candy.java
│ │ ├── ClimbingStairs.java
│ │ ├── CloneGraph.java
│ │ ├── CompareVersionNumbers.java
│ │ ├── ContainerWithMostWater.java
│ │ ├── ContainsDuplicate.java
│ │ ├── ContainsDuplicateII.java
│ │ ├── ContainsDuplicateIII.java
│ │ ├── ContiguousRanges.java
│ │ ├── CountAndSay.java
│ │ ├── CountNumbersWithUniqueDigits.java
│ │ ├── CovertSortedArrayToBnarySearchTree.java
│ │ ├── DeleteNodeInALinkedList.java
│ │ ├── DungeonGame.java
│ │ ├── EditDistance.java
│ │ ├── ExcelSheetColumnNumber.java
│ │ ├── ExcelSheetColumnTitle.java
│ │ ├── FactorialTrailingZeroes.java
│ │ ├── FindTheDifference.java
│ │ ├── FirstBadVersion.java
│ │ ├── FirstUniqueCharacterInAString.java
│ │ ├── FourSum.java
│ │ ├── GasStation.java
│ │ ├── GenerateParentheses.java
│ │ ├── HappyNumber.java
│ │ ├── HouseRobber.java
│ │ ├── HouseRobberIII.java
│ │ ├── ImplementQueueUsingStacks.java
│ │ ├── ImplementStackUsingQueues.java
│ │ ├── InsertionSortList.java
│ │ ├── IntegerBreak.java
│ │ ├── IntegerToRoman.java
│ │ ├── InterleavingString.java
│ │ ├── IntersectionOfTwoArrays.java
│ │ ├── IntersectionOfTwoLinkedLists.java
│ │ ├── IsomorphicStrings.java
│ │ ├── JumpGame2.java
│ │ ├── LargestRectangleInHistogram.java
│ │ ├── LengthOfLastWord.java
│ │ ├── LinkedListCycle.java
│ │ ├── LinkedListCycle2.java
│ │ ├── LongestConsecutiveSequence.java
│ │ ├── LongestPalindrome.java
│ │ ├── LongestSubstringWithoutRepeatingCharacters.java
│ │ ├── LowestCommonAncestorOfABinarySearchTree.java
│ │ ├── MajorityElement.java
│ │ ├── MaximumDepthOfBinaryTree.java
│ │ ├── MaximumProductOfWordLengths.java
│ │ ├── MaximumProductSubarray.java
│ │ ├── MaximumSubarray.java
│ │ ├── MedianFinder.java
│ │ ├── MedianOfTwoSortedArrays.java
│ │ ├── MergeSortedArray.java
│ │ ├── MergeTwoSortedLists.java
│ │ ├── MinStack.java
│ │ ├── MinimumPathSum.java
│ │ ├── MinimumWindowSubstring.java
│ │ ├── MoveZeroes.java
│ │ ├── NQueens.java
│ │ ├── NQueensII.java
│ │ ├── NimGame.java
│ │ ├── NumberOfDigitOne.java
│ │ ├── OddEvenLinkedList.java
│ │ ├── PalindromePartitioningII.java
│ │ ├── PartitionList.java
│ │ ├── PascalsTriangle.java
│ │ ├── PascalsTriangle2.java
│ │ ├── PathSum2.java
│ │ ├── PeekingIterator.java
│ │ ├── PermutationSequence.java
│ │ ├── Permutations.java
│ │ ├── Permutations2.java
│ │ ├── PlusOne.java
│ │ ├── PopulatingNextRightPointersInEachNode.java
│ │ ├── PowXN.java
│ │ ├── PowerOfThree.java
│ │ ├── PowerOfTwo.java
│ │ ├── ProductOfArrayExceptSelf.java
│ │ ├── QueueReconstructionByHeight.java
│ │ ├── RangeSumQueryImmutable.java
│ │ ├── RansomNote.java
│ │ ├── RectangleArea.java
│ │ ├── RemoveDuplicatesFromSortedArray.java
│ │ ├── RemoveDuplicatesFromSortedArrayII.java
│ │ ├── RemoveDuplicatesFromSortedList.java
│ │ ├── RemoveDuplicatesFromSortedListII.java
│ │ ├── RemoveElement.java
│ │ ├── RestoreIpAddresses.java
│ │ ├── ReverseInteger.java
│ │ ├── ReverseLinkedList.java
│ │ ├── ReverseString.java
│ │ ├── ReverseVowelsOfAString.java
│ │ ├── ReverseWordsInAString.java
│ │ ├── RomanToInteger.java
│ │ ├── RotateArray.java
│ │ ├── RotateImage.java
│ │ ├── RotateList.java
│ │ ├── SameTree.java
│ │ ├── SearchA2DMatrix.java
│ │ ├── SearchA2DMatrix2.java
│ │ ├── SearchForARange.java
│ │ ├── SearchInsertPosition.java
│ │ ├── SetMatrixZeroes.java
│ │ ├── ShortestPalindrome.java
│ │ ├── SimplifyPath.java
│ │ ├── SingleNumber.java
│ │ ├── SingleNumber2.java
│ │ ├── SingleNumberIII.java
│ │ ├── SortColors.java
│ │ ├── SpiralMatrixII.java
│ │ ├── SumOfLeftLeaves.java
│ │ ├── SumRootToLeafNumbers.java
│ │ ├── SurroundedRegions.java
│ │ ├── SwapNodesInPairs.java
│ │ ├── SymmetricTree.java
│ │ ├── ThreeSum.java
│ │ ├── ThreeSumClosest.java
│ │ ├── TopKFrequentElements.java
│ │ ├── TwoSum.java
│ │ ├── TwoSumII.java
│ │ ├── UglyNumber.java
│ │ ├── UglyNumber2.java
│ │ ├── UniqueBinarySearchTrees.java
│ │ ├── UniquePaths.java
│ │ ├── ValidAnagram.java
│ │ ├── ValidNumber.java
│ │ ├── ValidPalindrome.java
│ │ ├── ValidParentheses.java
│ │ ├── ValidSudoku.java
│ │ ├── WildcardMatching.java
│ │ ├── WordBreakII.java
│ │ ├── WordLadder2.java
│ │ ├── WordPattern.java
│ │ └── commons
│ │ ├── ListNode.java
│ │ ├── TreeLinkNode.java
│ │ ├── TreeNode.java
│ │ └── UndirectedGraphNode.java
└── python
│ └── pyleetcode
│ ├── Array_Partition_I.py
│ ├── Binary_Tree_Tilt.py
│ ├── Construct_String_from_Binary_Tree.py
│ ├── Merge_Two_Binary_Trees.py
│ ├── Relative_Ranks.py
│ ├── Reverse_Words_in_a_String_III.py
│ ├── Single_Element_in_a_Sorted_Array.py
│ ├── assign_cookies.py
│ ├── base_7.py
│ ├── binary_watch.py
│ ├── construct_rectangle.py
│ ├── defanging_an_ip_address.py
│ ├── detect_capital.py
│ ├── find_disappeared_numbers.py
│ ├── fizz_buzz.py
│ ├── hamming_distance.py
│ ├── island_perimeter.py
│ ├── jewels_and_stones.py
│ ├── judge_route_circle.py
│ ├── keyboard_row.py
│ ├── max_consecutive_ones.py
│ ├── minimum_absolute_difference_in_BST.py
│ ├── minimum_moves_to_equal_array_elements.py
│ ├── next_greater_element.py
│ ├── number_complement.py
│ ├── reverse_string_ii.py
│ ├── split_a_string_in_balanced_strings.py
│ ├── string-to-interger-atoi.py
│ └── utils.py
└── test
└── java
└── com
└── pengyifan
└── leetcode
├── ArrayBalancePointTest.java
├── BestTimeToBuyAndSellStockIITest.java
├── BestTimeToBuyAndSellStockTest.java
├── BinaryTreePathsTest.java
├── BullsAndCowsTest.java
├── CandyTest.java
├── CompareVersionNumbersTest.java
├── ContainerWithMostWaterTest.java
├── ContainsDuplicateIIITest.java
├── ContiguousRangesTest.java
├── CountAndSayTest.java
├── DeleteNodeInALinkedListTest.java
├── DungeonGameTest.java
├── EditDistanceTest.java
├── FactorialTrailingZeroesTest.java
├── FindTheDifferenceTest.java
├── FirstBadVersionTest.java
├── FourSumTest.java
├── GasStationTest.java
├── GenerateParenthesesTest.java
├── HappyNumberTest.java
├── HouseRobberIIITest.java
├── HouseRobberTest.java
├── IntegerBreakTest.java
├── IntegerToEnglishWords.java
├── IntegerToEnglishWordsTest.java
├── InterleavingStringTest.java
├── InvertBinaryTree.java
├── JumpGame2Test.java
├── KthSmallestElementInABST.java
├── LargestRectangleInHistogramTest.java
├── LengthOfLastWordTest.java
├── LinkedListCycle2Test.java
├── LongestConsecutiveSequenceTest.java
├── LongestPalindromeTest.java
├── LongestSubstringWithoutRepeatingCharactersTest.java
├── LowestCommonAncestorOfABinaryTree.java
├── MaximumProductOfWordLengthsTest.java
├── MaximumProductSubarrayTest.java
├── MedianFinderTest.java
├── MedianOfTwoSortedArraysTest.java
├── MergeSortedArrayTest.java
├── MinimumPathSumTest.java
├── MinimumWindowSubstringTest.java
├── MissingNumber.java
├── MissingNumberTest.java
├── NumberOfDigitOneTest.java
├── OddEvenLinkedListTest.java
├── PalindromeLinkedList.java
├── PalindromePartitioningIITest.java
├── PartitionListTest.java
├── PascalsTriangle2Test.java
├── PascalsTriangleTest.java
├── PermutationSequenceTest.java
├── Permutations2Test.java
├── PermutationsTest.java
├── QueueReconstructionByHeightTest.java
├── RectangleAreaTest.java
├── RemoveDuplicatesFromSortedArrayTest.java
├── RemoveDuplicatesFromSortedListIITest.java
├── RemoveLinkedListElements.java
├── RemoveLinkedListElementsTest.java
├── RestoreIpAddressesTest.java
├── ReverseLinkedListTest.java
├── ReverseVowelsOfAStringTest.java
├── ReverseWordsInAStringTest.java
├── RomanToIntegerTest.java
├── RotateArrayTest.java
├── RotateImageTest.java
├── RotateListTest.java
├── SearchForARangeTest.java
├── SearchInsertPositionTest.java
├── SetMatrixZeroesTest.java
├── ShortestPalindromeTest.java
├── SimplifyPathTest.java
├── SingleNumber2Test.java
├── SortColorsTest.java
├── SumRootToLeafNumbersTest.java
├── SurroundedRegionsTest.java
├── ThreeSumClosestTest.java
├── ThreeSumTest.java
├── TopKFrequentElementsTest.java
├── TwoSumIITest.java
├── TwoSumTest.java
├── UglyNumber2Test.java
├── UglyNumberTest.java
├── UniquePathsTest.java
├── ValidAnagramTest.java
├── ValidNumberTest.java
├── ValidPalindromeTest.java
├── ValidParenthesesTest.java
├── ValidSudokuTest.java
├── WildcardMatchingTest.java
├── WordBreakIITest.java
├── WordLadder2Test.java
└── WordPatternTest.java
/.project:
--------------------------------------------------------------------------------
1 |
2 |
6 | * For example, 7 | *
8 | * a = "11" 9 | *
10 | * b = "1" 11 | *
12 | * Return "100". 13 | */ 14 | public class AddBinary { 15 | public String addBinary(String a, String b) { 16 | if (a.length() < b.length()) { 17 | String tmp = a; 18 | a = b; 19 | b = tmp; 20 | } 21 | String s = ""; 22 | int ai = a.length() - 1; 23 | int bi = b.length() - 1; 24 | boolean carry = false; 25 | while (bi >= 0) { 26 | char ac = a.charAt(ai); 27 | char bc = b.charAt(bi); 28 | if ((ac == '0' && bc == '1') || (ac == '1' && bc == '0')) { 29 | s = (carry ? '0' : '1') + s; 30 | } else if ((ac == '0' && bc == '0')) { 31 | s = (carry ? '1' : '0') + s; 32 | carry = false; 33 | } else { 34 | s = (carry ? '1' : '0') + s; 35 | carry = true; 36 | } 37 | ai--; 38 | bi--; 39 | } 40 | while (ai >= 0) { 41 | char ac = a.charAt(ai); 42 | if (ac == '0') { 43 | s = (carry ? '1' : '0') + s; 44 | carry = false; 45 | } else { 46 | s = (carry ? '0' : '1') + s; 47 | } 48 | ai--; 49 | } 50 | if (carry) { 51 | s = '1' + s; 52 | } 53 | return s; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/AddDigits.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given a non-negative integer num, repeatedly add all its digits until the result has only one 5 | * digit. 6 | *
7 | * For example: 8 | *
9 | * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return 10 | * it. 11 | *
12 | * Follow up: 13 | * Could you do it without any loop/recursion in O(1) runtime? 14 | */ 15 | public class AddDigits { 16 | public int addDigits(int num) { 17 | return addDigitsHelper(num); 18 | } 19 | 20 | private int addDigitsHelper(int num) { 21 | if (num < 10) { 22 | return num; 23 | } 24 | int i = 0; 25 | while (num != 0) { 26 | i += num % 10; 27 | num = num / 10; 28 | } 29 | return addDigitsHelper(i); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/ArrayBalancePoint.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Array balance point. Find, if possible, an index in the array such that the 5 | * sum of all integers to left of the index is equal to the sum of all the 6 | * integers right of the index. e.g. 7 | * 8 | *
9 | * balancePoint([5, 4, 0, 19, 3, 4, 2, 0]) = 3 10 | * balancePoint([5, 4, 2, 1]) = -1 11 | * balancePoint([5, 4, 0, 3, 4, 2, 0]) = 2 12 | *13 | */ 14 | public class ArrayBalancePoint { 15 | 16 | public int balancePoint(int[] array) { 17 | if (array == null || array.length == 0) { 18 | return -1; 19 | } 20 | 21 | int sum = 0; 22 | for (int i : array) { 23 | sum += i; 24 | } 25 | 26 | int bp = -1; 27 | int leftSum = 0; 28 | for (int i = 0; i < array.length - 2; i++) { 29 | leftSum += array[i]; 30 | if (leftSum == (sum - array[i + 1]) / 2) { 31 | if (bp == -1) { 32 | bp = i + 1; 33 | } else { 34 | return -1; 35 | } 36 | } 37 | } 38 | return bp; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/BalancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import com.pengyifan.leetcode.commons.TreeNode; 4 | 5 | /** 6 | * Given a binary tree, determine if it is height-balanced. 7 | *
8 | * For this problem, a height-balanced binary tree is defined as a binary tree 9 | * in which the depth of the two subtrees of every node never differ by more 10 | * than 1. 11 | */ 12 | public class BalancedBinaryTree { 13 | 14 | public boolean isBalanced(TreeNode root) { 15 | if (root == null) { 16 | return true; 17 | } 18 | return helper(root).b; 19 | } 20 | 21 | public Pair helper(TreeNode root) { 22 | if (root == null) { 23 | return new Pair(true, 0); 24 | } 25 | Pair left = helper(root.left); 26 | Pair right = helper(root.right); 27 | if (!left.b || !right.b) { 28 | return new Pair(false, -1); 29 | } 30 | if (Math.abs(left.height - right.height) <= 1) { 31 | return new Pair(true, Math.max(left.height, right.height) + 1); 32 | } 33 | return new Pair(false, -1); 34 | } 35 | 36 | class Pair { 37 | 38 | int height; 39 | boolean b; 40 | 41 | Pair(boolean b, int height) { 42 | this.b = b; 43 | this.height = height; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Say you have an array for which the ith element is the price of a given 5 | * stock on day i. 6 | *
7 | * If you were only permitted to complete at most one transaction (ie, buy one 8 | * and sell one share of the stock), design an algorithm to find the maximum 9 | * profit. 10 | */ 11 | public class BestTimeToBuyAndSellStock { 12 | 13 | public int maxProfit(int[] prices) { 14 | if (prices == null || prices.length == 0 || prices.length == 1) { 15 | return 0; 16 | } 17 | int[] mins = new int[prices.length]; 18 | 19 | mins[0] = prices[0]; 20 | int min = prices[0]; 21 | for (int i = 1; i < prices.length; i++) { 22 | if (prices[i] < min) { 23 | min = prices[i]; 24 | } 25 | mins[i] = min; 26 | } 27 | int max = 0; 28 | for (int i = 0; i < prices.length; i++) { 29 | if (max < prices[i] - mins[i]) { 30 | max = prices[i] - mins[i]; 31 | } 32 | } 33 | return max; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/BestTimeToBuyAndSellStockII.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Say you have an array for which the ith element is the price of a given 5 | * stock on day i. 6 | *
7 | * Design an algorithm to find the maximum profit. You may complete as many 8 | * transactions as you like (ie, buy one and sell one share of the stock 9 | * multiple times). However, you may not engage in multiple transactions at the 10 | * same time (ie, you must sell the stock before you buy again). 11 | */ 12 | public class BestTimeToBuyAndSellStockII { 13 | 14 | public int maxProfit(int[] prices) { 15 | if (prices == null || prices.length == 0 || prices.length == 1) { 16 | return 0; 17 | } 18 | int res = 0; 19 | for (int i = 1; i < prices.length; i++) { 20 | if (prices[i] > prices[i - 1]) { 21 | res += prices[i] - prices[i - 1]; 22 | } 23 | } 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/BinaryTreeInorderTraversal.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Stack; 5 | 6 | import com.pengyifan.leetcode.commons.TreeNode; 7 | 8 | /** 9 | * Given a binary tree, return the inorder traversal of its nodes' values. 10 | *
11 | * For example: Given binary tree {1,#,2,3}, 12 | * 13 | *
14 | * 1 15 | * \ 16 | * 2 17 | * / 18 | * 3 19 | *20 | * 21 | * return [1,3,2]. 22 | *
23 | * Note: Recursive solution is trivial, could you do it iteratively?
24 | */
25 | public class BinaryTreeInorderTraversal {
26 |
27 | public ArrayList
9 | * Example:
10 | *
11 | * Given n = 3.
12 | *
13 | * At first, the three bulbs are [off, off, off].
14 | * After first round, the three bulbs are [on, on, on].
15 | * After second round, the three bulbs are [on, off, on].
16 | * After third round, the three bulbs are [on, off, off].
17 | *
18 | * So you should return 1, because there is only one bulb is on.
19 | *
20 | * --> "on" or "off" at each position in an array of length n?
21 | *
22 | * --> toggle even number times will result in "on", toggle odd number times will result in "off"
23 | *
24 | * --> for position k, the number of toggles is the number of distinct divisors that k has
25 | *
26 | * --> divisors always come in pair, which means even number of divisors, for example, 12 has
27 | * (1,12),(2,6),(3,4).
28 | *
29 | * --> however, Square Number has odd number of divisors, e.g. 25 has 1,25,5
30 | *
31 | * --> thus, the number of "on", is the number of perfect square number <= n
32 | */
33 | public class BulbSwitcher {
34 | public int bulbSwitch(int n) {
35 | return (int) Math.sqrt(n);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/Candy.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * There are N children standing in a line. Each child is assigned a rating
7 | * value.
8 | *
9 | * You are giving candies to these children subjected to the following
10 | * requirements:
11 | *
6 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can
7 | * you climb to the top?
8 | */
9 | public class ClimbingStairs {
10 |
11 | // fib
12 | public int climbStairs(int n) {
13 | if (n == 0) {
14 | return 0;
15 | } else if (n == 1) {
16 | return 1;
17 | } else if (n == 2) {
18 | return 2;
19 | }
20 | int sum = 0;
21 | int f1 = 1;
22 | int f2 = 2;
23 | for (int i = 3; i <= n; i++) {
24 | sum = f1 + f2;
25 | f1 = f2;
26 | f2 = sum;
27 | }
28 | return sum;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ContainsDuplicate.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * Given an array of integers, find if the array contains any duplicates. Your function should
8 | * return true if any value appears at least twice in the array, and it should return false if every
9 | * element is distinct.
10 | */
11 | public class ContainsDuplicate {
12 | public boolean containsDuplicate(int[] nums) {
13 | if (nums == null || nums.length == 0) {
14 | return false;
15 | }
16 | Set
7 | * 1 is read off as "one 1" or 11.
8 | *
9 | * 11 is read off as "two 1s" or 21.
10 | *
11 | * 21 is read off as "one 2, then one 1" or 1211.
12 | *
13 | * Given an integer n, generate the nth sequence.
14 | *
15 | * Note: The sequence of integers will be represented as a string.
16 | */
17 | public class CountAndSay {
18 | public String countAndSay(int n) {
19 | String s = "1";
20 | for (int i = 0; i < n - 1; i++) {
21 | s = countAndSayHelper(s);
22 | }
23 | return s;
24 | }
25 |
26 | private String countAndSayHelper(String s) {
27 | String o = "";
28 | char c = s.charAt(0);
29 | int n = 0;
30 | int i = 0;
31 | while (i < s.length()) {
32 | if (s.charAt(i) == c) {
33 | n++;
34 | i++;
35 | } else {
36 | o += Integer.toString(n) + c;
37 | c = s.charAt(i);
38 | n = 0;
39 | }
40 | }
41 | o += Integer.toString(n) + c;
42 | return o;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/CountNumbersWithUniqueDigits.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
8 | *
9 | * Example:
10 | * Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100,
11 | * excluding [11,22,33,44,55,66,77,88,99])
12 | *
13 | * f(0) = 1
14 | *
15 | * f(1) = 10
16 | *
17 | * f(2) = 9*9 + f(1)
18 | *
19 | * f(3) = 9*9*8 + f(2) + f(1)
20 | */
21 | public class CountNumbersWithUniqueDigits {
22 | public int countNumbersWithUniqueDigits(int n) {
23 | if (n == 0) {
24 | return 1;
25 | }
26 | List
9 | * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the
10 | * linked list should become 1 -> 2 -> 4 after calling your function.
11 | */
12 | public class DeleteNodeInALinkedList {
13 | public void deleteNode(ListNode node) {
14 | if (node.next == null) {
15 | return;
16 | }
17 | if (node.next.next == null) {
18 | node.val = node.next.val;
19 | node.next = null;
20 | return;
21 | }
22 | ListNode next = node.next;
23 | while (next.next != null) {
24 | node.val = next.val;
25 | node = next;
26 | next = next.next;
27 | }
28 | node.val = next.val;
29 | node.next = null;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/DungeonGame.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | public class DungeonGame {
4 |
5 | public int calculateMinimumHP(int[][] dungeon) {
6 | if (dungeon == null || dungeon.length == 0) {
7 | return 0;
8 | }
9 | int row = dungeon.length;
10 | int col = dungeon[0].length;
11 | int[][] dp = new int[row][col];
12 | for (int i = row - 1; i >= 0; i--) {
13 | for (int j = col - 1; j >= 0; j--) {
14 | if (i == row - 1 && j == col - 1) {
15 | dp[i][j] = dungeon[i][j] >= 0 ? 1 : 1 - dungeon[i][j];
16 | } else {
17 | int minToNext = (i == row - 1) ? dp[i][j + 1] :
18 | ((j == col - 1) ? dp[i + 1][j] : Math.min(dp[i + 1][j], dp[i][j + 1]));
19 | dp[i][j] = dungeon[i][j] >= minToNext ? 1 : minToNext - dungeon[i][j];
20 | }
21 | }
22 | }
23 | return dp[0][0];
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/EditDistance.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Given two words word1 and word2, find the minimum number of steps required
7 | * to convert word1 to word2. (each operation is counted as 1 step.)
8 | *
9 | * You have the following 3 operations permitted on a word:
10 | *
6 | * Given a column title as appear in an Excel sheet, return its corresponding column number.
7 | *
8 | * For example:
9 | *
6 | * For example:
7 | *
6 | * Note: Your solution should be in logarithmic time complexity.
7 | */
8 | public class FactorialTrailingZeroes {
9 | public int trailingZeroes(int n) {
10 | int sum = 0;
11 | while (n != 0) {
12 | n /= 5;
13 | sum += n;
14 | }
15 | return sum;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/FindTheDifference.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given two strings s and t which consist of only lowercase letters.
5 | *
6 | * String t is generated by random shuffling string s and then add one more letter at a random
7 | * position.
8 | *
9 | * Find the letter that was added in t.
10 | *
11 | * Example:
12 | *
9 | * Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which
10 | * causes all the following ones to be bad.
11 | *
12 | * You are given an API bool isBadVersion(version) which will return whether version is bad.
13 | * Implement a function to find the first bad version. You should minimize the number of calls to
14 | * the API.
15 | */
16 | public class FirstBadVersion extends VersionControl {
17 |
18 | public FirstBadVersion(int firstBadVersion) {
19 | super(firstBadVersion);
20 | }
21 |
22 | public int firstBadVersion(int n) {
23 | int from = 1;
24 | int to = n;
25 | while (from < to) {
26 | int mid = from + (to - from) / 2;
27 | if (isBadVersion(mid)) {
28 | to = mid;
29 | } else {
30 | from = mid + 1;
31 | }
32 | }
33 | return isBadVersion(to) ? to : -1;
34 | }
35 | }
36 |
37 | abstract class VersionControl {
38 | public int firstBadVersion;
39 |
40 | public VersionControl(int firstBadVersion) {
41 | this.firstBadVersion = firstBadVersion;
42 | }
43 |
44 | boolean isBadVersion(int version) {
45 | return version >= firstBadVersion;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/FirstUniqueCharacterInAString.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given a string, find the first non-repeating character in it and return it's index. If it doesn't
5 | * exist, return -1.
6 | *
7 | * Examples:
8 | *
7 | * You have a car with an unlimited gas tank and it costs cost[i] of gas to
8 | * travel from station i to its next station (i+1). You begin the journey with
9 | * an empty tank at one of the gas stations.
10 | *
11 | * Return the starting gas station's index if you can travel around the circuit
12 | * once, otherwise return -1.
13 | */
14 | public class GasStation {
15 |
16 | public int canCompleteCircuit(int[] gas, int[] cost) {
17 | if (gas == null
18 | || cost == null
19 | || gas.length == 0
20 | || cost.length == 0
21 | || gas.length != cost.length) {
22 | return -1;
23 | }
24 | int length = gas.length;
25 | gas = doubleArray(gas);
26 | cost = doubleArray(cost);
27 |
28 | int start = 0;
29 | int tank = 0;
30 |
31 | for (int end = 1; end < gas.length; end++) {
32 | tank += gas[end - 1] - cost[end - 1];
33 | if (tank < 0) {
34 | start = end;
35 | tank = 0;
36 | }
37 | if (end - start == length) {
38 | return start;
39 | }
40 | }
41 |
42 | return -1;
43 | }
44 |
45 | private int[] doubleArray(int[] array) {
46 | int[] results = new int[array.length + array.length];
47 | System.arraycopy(array, 0, results, 0, array.length);
48 | System.arraycopy(array, 0, results, array.length, array.length);
49 | return results;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/GenerateParentheses.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.List;
6 |
7 | /**
8 | * Given n pairs of parentheses, write a function to generate all combinations
9 | * of well-formed parentheses.
10 | *
11 | * For example, given n = 3, a solution set is:
12 | *
13 | * "((()))", "(()())", "(())()", "()(())", "()()()"
14 | *
15 | */
16 | public class GenerateParentheses {
17 |
18 | public List
6 | * A happy number is a number defined by the following process: Starting with any positive integer,
7 | * replace the number by the sum of the squares of its digits, and repeat the process until the
8 | * number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
9 | * Those numbers for which this process ends in 1 are happy numbers.
10 | *
11 | * Example: 19 is a happy number
12 | *
9 | * Given a list of non-negative integers representing the amount of money of each house, determine
10 | * the maximum amount of money you can rob tonight without alerting the police.
11 | */
12 | public class HouseRobber {
13 | public int rob(int[] nums) {
14 | if (nums == null || nums.length == 0) {
15 | return 0;
16 | }
17 | int[] mem = new int[nums.length];
18 | for (int i = 0; i < mem.length; i++) {
19 | mem[i] = Integer.MIN_VALUE;
20 | }
21 | robHelper(nums, 0, mem);
22 | return mem[0];
23 | }
24 |
25 | private int robHelper(int[] nums, int from, int[] mem) {
26 | if (from == nums.length - 1) {
27 | mem[from] = nums[from];
28 | return nums[from];
29 | }
30 | if (from >= nums.length) {
31 | return 0;
32 | }
33 | if (mem[from] == Integer.MIN_VALUE) {
34 | int i1 = nums[from] + robHelper(nums, from + 2, mem);
35 | int i2 = nums[from + 1] + robHelper(nums, from + 3, mem);
36 | mem[from] = Math.max(i1, i2);
37 | }
38 | return mem[from];
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/InsertionSortList.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Sort a linked list using insertion sort.
7 | */
8 | public class InsertionSortList {
9 |
10 | public ListNode insertionSortList(ListNode head) {
11 | if (head == null || head.next == null) {
12 | return head;
13 | }
14 | ListNode cur = head;
15 | while (cur.next != null) {
16 | ListNode x = cur.next;
17 | cur.next = cur.next.next;
18 | ListNode tmp = head;
19 | if (x.val < tmp.val) {
20 | x.next = tmp;
21 | head = x;
22 | } else {
23 | while (tmp.next != cur.next && tmp.next.val < x.val) {
24 | tmp = tmp.next;
25 | }
26 | if (tmp.next != cur.next) {
27 | x.next = tmp.next;
28 | tmp.next = x;
29 | } else {
30 | x.next = tmp.next;
31 | tmp.next = x;
32 | cur = cur.next;
33 | }
34 | }
35 | }
36 | return head;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/IntegerBreak.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given a positive integer n, break it into the sum of at least two positive integers and maximize
5 | * the product of those integers. Return the maximum product you can get.
6 | *
7 | * For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
8 | *
9 | * Note: you may assume that n is not less than 2.
10 | */
11 | public class IntegerBreak {
12 |
13 | public int integerBreak(int n) {
14 | if (n == 2) {
15 | return 1;
16 | }
17 | if (n == 3) {
18 | return 2;
19 | }
20 | if (n == 4) {
21 | return 4;
22 | }
23 | // 5 6 7 Group 1
24 | // 32 33 34
25 | // 8 9 10 Group 2
26 | // 332 333 334
27 | // 11 12 13 Group 3
28 | // 3332 3333 3334
29 | int groupNumber = (n - 5) / 3 + 1;
30 | int addition = n - 3 * (groupNumber);
31 | int res = (int)(Math.pow(3, groupNumber)) * addition;
32 | return res;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/IntegerToRoman.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given an integer, convert it to a roman numeral.
5 | *
6 | * Input is guaranteed to be within the range from 1 to 3999.
7 | */
8 | public class IntegerToRoman {
9 | public String intToRoman(int num) {
10 | StringBuilder sb = new StringBuilder();
11 | while (num > 0) {
12 | if (num >= 1000) {
13 | sb.append('M');
14 | num -= 1000;
15 | } else if (num >= 900) {
16 | sb.append("CM");
17 | num -= 900;
18 | } else if (num >= 500) {
19 | sb.append('D');
20 | num -= 500;
21 | } else if (num >= 400) {
22 | sb.append("CD");
23 | num -= 400;
24 | } else if (num >= 100) {
25 | sb.append('C');
26 | num -= 100;
27 | } else if (num >= 90) {
28 | sb.append("XC");
29 | num -= 90;
30 | } else if (num >= 50) {
31 | sb.append('L');
32 | num -= 50;
33 | } else if (num >= 40) {
34 | sb.append("XL");
35 | num -= 40;
36 | } else if (num >= 10) {
37 | sb.append('X');
38 | num -= 10;
39 | } else if (num >= 9) {
40 | sb.append("IX");
41 | num -= 9;
42 | } else if (num >= 5) {
43 | sb.append('V');
44 | num -= 5;
45 | } else if (num >= 4) {
46 | sb.append("IV");
47 | num -= 4;
48 | } else if (num >= 1) {
49 | sb.append('I');
50 | num -= 1;
51 | }
52 | }
53 | return sb.toString();
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/InterleavingString.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and
5 | * s2.
6 | */
7 | public class InterleavingString {
8 |
9 | public boolean isInterleave(String s1, String s2, String s3) {
10 | if (s1 == null || s2 == null || s3 == null) {
11 | return false;
12 | }
13 | if (s1.isEmpty() && s2.isEmpty() && s3.isEmpty()) {
14 | return true;
15 | }
16 | if (s1.isEmpty()) {
17 | return s2.equals(s3);
18 | }
19 | if (s2.isEmpty()) {
20 | return s1.equals(s3);
21 | }
22 | if (s1.length() + s2.length() != s3.length()) {
23 | return false;
24 | }
25 | boolean[][] t = new boolean[s1.length() + 1][s2.length() + 1];
26 | t[0][0] = true;
27 | for (int i = 0; i <= s1.length(); i++) {
28 | for (int j = 0; j <= s2.length(); j++) {
29 | if (i > 0) {
30 | t[i][j] = (t[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1));
31 | }
32 | if (j > 0) {
33 | t[i][j] |= (t[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1));
34 | }
35 | }
36 | }
37 | return t[s1.length()][s2.length()]
38 | | t[s1.length() - 1][s2.length()]
39 | | t[s1.length()][s2.length() - 1];
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/IntersectionOfTwoArrays.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.HashSet;
4 |
5 | /**
6 | * Given two arrays, write a function to compute their intersection.
7 | *
8 | * Example:
9 | * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
10 | *
11 | * Note:
12 | * Each element in the result must be unique.
13 | * The result can be in any order.
14 | */
15 | public class IntersectionOfTwoArrays {
16 | public int[] intersection(int[] nums1, int[] nums2) {
17 | if (nums1 == null || nums2==null) {
18 | return null;
19 | }
20 | HashSet
9 | * Two strings are isomorphic if the characters in s can be replaced to get t.
10 | *
11 | * All occurrences of a character must be replaced with another character while preserving the order
12 | * of characters. No two characters may map to the same character but a character may map to
13 | * itself.
14 | *
15 | * For example,
16 | * Given "egg", "add", return true.
17 | *
18 | * Given "foo", "bar", return false.
19 | *
20 | * Given "paper", "title", return true.
21 | *
22 | * Note:
23 | * You may assume both s and t have the same length.
24 | */
25 | public class IsomorphicStrings {
26 | public boolean isIsomorphic(String s, String t) {
27 | if (s == null || t == null || s.length() != t.length()) {
28 | return false;
29 | }
30 | Map
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
10 | * characters only.
11 | *
12 | * For example, Given s = "Hello World", return 5.
13 | */
14 | public class LengthOfLastWord {
15 |
16 | public int lengthOfLastWord(String s) {
17 | if (s == null || s.isEmpty()) {
18 | return 0;
19 | }
20 | int length = 0;
21 | int lastLength = 0;
22 | int state = 0;
23 | for (int i = 0; i < s.length(); i++) {
24 | char c = s.charAt(i);
25 | switch (state) {
26 | case 0:
27 | if (c == ' ') {
28 | ;
29 | } else {
30 | state = 1;
31 | length = 1;
32 | }
33 | break;
34 | case 1:
35 | if (c == ' ') {
36 | lastLength = length;
37 | length = 0;
38 | state = 0;
39 | } else {
40 | length++;
41 | }
42 | }
43 | }
44 | if (length != 0) {
45 | return length;
46 | } else {
47 | return lastLength;
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/LinkedListCycle.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Given a linked list, determine if it has a cycle in it.
7 | *
8 | * Follow up: Can you solve it without using extra space?
9 | */
10 | public class LinkedListCycle {
11 |
12 | public boolean hasCycle(ListNode head) {
13 | if (head == null) {
14 | return false;
15 | }
16 | if (head.next == null) {
17 | return false;
18 | }
19 | if (head.next == head) {
20 | return true;
21 | }
22 | if (head.next.next == null) {
23 | return false;
24 | }
25 | ListNode slow = head.next;
26 | ListNode fast = head.next.next;
27 | while (slow != fast) {
28 | slow = slow.next;
29 | if (fast.next == null) {
30 | return false;
31 | } else if (fast.next.next == null) {
32 | return false;
33 | }
34 | fast = fast.next.next;
35 | }
36 |
37 | return true;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/LinkedListCycle2.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Given a linked list, return the node where the cycle begins. If there is no
7 | * cycle, return null.
8 | *
9 | * Follow up: Can you solve it without using extra space?
10 | */
11 | public class LinkedListCycle2 {
12 |
13 | public ListNode detectCycle(ListNode head) {
14 | if (head == null) {
15 | return null;
16 | }
17 | ListNode begin1 = head;
18 | ListNode begin2 = head;
19 | begin1 = begin1.next;
20 | begin2 = begin2.next;
21 | if (begin2 == null) {
22 | return null;
23 | }
24 | begin2 = begin2.next;
25 | if (begin2 == null) {
26 | return null;
27 | }
28 | while (begin1 != begin2) {
29 | begin1 = begin1.next;
30 | begin2 = begin2.next;
31 | if (begin2 == null) {
32 | return null;
33 | }
34 | begin2 = begin2.next;
35 | if (begin2 == null) {
36 | return null;
37 | }
38 | }
39 | begin1 = head;
40 | while (begin1 != begin2) {
41 | begin1 = begin1.next;
42 | begin2 = begin2.next;
43 | }
44 | return begin1;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/LongestConsecutiveSequence.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * Given an unsorted array of integers, find the length of the longest
8 | * consecutive elements sequence.
9 | *
10 | * For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements
11 | * sequence is [1, 2, 3, 4]. Return its length: 4.
12 | *
13 | * Your algorithm should run in O(n) complexity.
14 | */
15 | public class LongestConsecutiveSequence {
16 |
17 | public int longestConsecutive(int[] num) {
18 | if (num == null || num.length == 0) {
19 | return 0;
20 | }
21 | int maxLength = 0;
22 | // number, visited
23 | Set
7 | * This is case sensitive, for example "Aa" is not considered a palindrome here.
8 | *
9 | * Note:
10 | * Assume the length of given string will not exceed 1,010.
11 | *
12 | * Example:
13 | *
9 | * Examples:
10 | *
11 | * Given "abcabcbb", the answer is "abc", which the length is 3.
12 | *
13 | * Given "bbbbb", the answer is "b", with the length of 1.
14 | *
15 | * Given "pwwkew", the answer is "wke", with the length of 3.
16 | *
17 | * Note that the answer must be a
18 | * substring, "pwke" is a subsequence and not a substring.
19 | */
20 | public class LongestSubstringWithoutRepeatingCharacters {
21 | public int lengthOfLongestSubstring(String s) {
22 | if (s == null || s.isEmpty()) {
23 | return 0;
24 | }
25 | int max = 0;
26 | int begin = 0;
27 | Map
9 | * You may assume that the array is non-empty and the majority element always exist in the array.
10 | */
11 | public class MajorityElement {
12 | public int majorityElement(int[] nums) {
13 | HashMap
8 | * The maximum depth is the number of nodes along the longest path from the
9 | * root node down to the farthest leaf node.
10 | */
11 | public class MaximumDepthOfBinaryTree {
12 |
13 | public int maxDepth(TreeNode root) {
14 | if (root == null) {
15 | return 0;
16 | }
17 | return maxDepthHelper(root);
18 | }
19 |
20 | private int maxDepthHelper(TreeNode node) {
21 | if (node.left == null && node.right == null) {
22 | return 1;
23 | } else if (node.left == null) {
24 | return maxDepth(node.right) + 1;
25 | } else if (node.right == null) {
26 | return maxDepth(node.left) + 1;
27 | } else {
28 | return Math.max(maxDepth(node.left), maxDepth(node.right)) + 1;
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/MaximumSubarray.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Find the contiguous subarray within an array (containing at least one
5 | * number) which has the largest sum.
6 | *
7 | * For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous
8 | * subarray [4,−1,2,1] has the largest sum = 6.
9 | *
10 | * More practice:
11 | *
12 | * If you have figured out the O(n) solution, try coding another solution using
13 | * the divide and conquer approach, which is more subtle.
14 | */
15 | public class MaximumSubarray {
16 |
17 | public int maxSubArray(int[] A) {
18 | if (A == null || A.length == 0) {
19 | return 0;
20 | }
21 | int max = Integer.MIN_VALUE;
22 | int sum = 0;
23 | for (int i : A) {
24 | sum = sum < 0 ? i : sum + i;
25 | max = Math.max(max, sum);
26 | }
27 | return max;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/MergeSortedArray.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given two sorted integer arrays A and B, merge B into A as one sorted array.
5 | *
6 | * Note:
7 | *
8 | * You may assume that A has enough space (size that is greater or equal to m +
9 | * n) to hold additional elements from B. The number of elements initialized in
10 | * A and B are m and n respectively.
11 | */
12 | public class MergeSortedArray {
13 |
14 | public void merge(int A[], int m, int B[], int n) {
15 | if (m < 0 || n < 0) {
16 | return;
17 | }
18 | if (m == 0 && n == 0) {
19 | return;
20 | }
21 | if (n == 0) {
22 | return;
23 | }
24 | if (m == 0) {
25 | System.arraycopy(B, 0, A, 0, n);
26 | }
27 | int indexA = m - 1;
28 | int indexB = n - 1;
29 | int totalIndex = m + n - 1;
30 | while (indexA >= 0 && indexB >= 0) {
31 | if (A[indexA] >= B[indexB]) {
32 | A[totalIndex] = A[indexA];
33 | indexA--;
34 | } else {
35 | A[totalIndex] = B[indexB];
36 | indexB--;
37 | }
38 | totalIndex--;
39 | }
40 | if (indexA < 0) {
41 | while (indexB >= 0) {
42 | A[totalIndex] = B[indexB];
43 | indexB--;
44 | totalIndex--;
45 | }
46 | } else {
47 | while (indexA >= 0) {
48 | A[totalIndex] = A[indexA];
49 | indexA--;
50 | totalIndex--;
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/MergeTwoSortedLists.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Merge two sorted linked lists and return it as a new list. The new list
7 | * should be made by splicing together the nodes of the first two lists.
8 | */
9 | public class MergeTwoSortedLists {
10 |
11 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
12 | if (l1 == null) {
13 | return l2;
14 | }
15 | if (l2 == null) {
16 | return l1;
17 | }
18 | ListNode l;
19 | if (l1.val <= l2.val) {
20 | l = l1;
21 | l1 = l1.next;
22 | } else {
23 | l = l2;
24 | l2 = l2.next;
25 | }
26 | ListNode cur = l;
27 | while (l1 != null && l2 != null) {
28 | if (l1.val <= l2.val) {
29 | cur.next = l1;
30 | cur = l1;
31 | l1 = l1.next;
32 | } else {
33 | cur.next = l2;
34 | cur = l2;
35 | l2 = l2.next;
36 | }
37 | }
38 | if (l1 != null) {
39 | cur.next = l1;
40 | } else {
41 | cur.next = l2;
42 | }
43 | return l;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/MinStack.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * Design a stack that supports push, pop, top, and retrieving the minimum element in constant
7 | * time.
8 | *
7 | * For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3,
8 | * 12, 0, 0].
9 | *
10 | * Note:
11 | *
12 | * You must do this in-place without making a copy of the array.
13 | * Minimize the total number of operations.
14 | */
15 | public class MoveZeroes {
16 | public void moveZeroes(int[] nums) {
17 | int begin = 0;
18 | int i = 0;
19 |
20 | while (i < nums.length) {
21 | if (nums[i] == 0) {
22 | i++;
23 | } else {
24 | nums[begin] = nums[i];
25 | begin++;
26 | i++;
27 | }
28 | }
29 |
30 | while (begin < nums.length) {
31 | nums[begin] = 0;
32 | begin++;
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/NQueensII.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Now, instead outputting board configurations, return the total number of
7 | * distinct solutions.
8 | */
9 | public class NQueensII {
10 |
11 | public int totalNQueens(int n) {
12 | if (n <= 0) {
13 | return 0;
14 | }
15 | int[] queens = new int[n];
16 | Arrays.fill(queens, -1);
17 | return solveNQueensHelper(queens, 0);
18 | }
19 |
20 | private int solveNQueensHelper(int[] queens, int currentRow) {
21 | if (currentRow == queens.length) {
22 | return 1;
23 | }
24 | int result = 0;
25 | for (int j = 0; j < queens.length; j++) {
26 | queens[currentRow] = j;
27 | if (isValid(queens, currentRow)) {
28 | result += solveNQueensHelper(queens, currentRow + 1);
29 | }
30 | }
31 | return result;
32 | }
33 |
34 | private boolean isValid(int[] queens, int currentRow) {
35 | for (int i = 0; i < currentRow; i++) {
36 | // same column
37 | if (queens[i] == queens[currentRow]) {
38 | return false;
39 | }
40 | // diagonal
41 | if (Math.abs(queens[i] - queens[currentRow]) == currentRow - i) {
42 | return false;
43 | }
44 | }
45 | return true;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/NimGame.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * You are playing the following Nim Game with your friend: There is a heap of stones on the table,
5 | * each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will
6 | * be the winner. You will take the first turn to remove the stones.
7 | *
8 | * Both of you are very clever and have optimal strategies for the game. Write a function to
9 | * determine whether you can win the game given the number of stones in the heap.
10 | *
11 | * For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2,
12 | * or 3 stones you remove, the last stone will always be removed by your friend.
13 | */
14 | public class NimGame {
15 | public boolean canWinNim(int n) {
16 | return n % 4 != 0;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/NumberOfDigitOne.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | public class NumberOfDigitOne {
4 | public int countDigitOne(int n) {
5 | if (n == 0) {
6 | return 0;
7 | } else if (1 <= n && n <= 9) {
8 | return 1;
9 | }
10 | // x: first digit
11 | int y = 1;
12 | int x = n;
13 | while (x >= 10) {
14 | x /= 10;
15 | y *= 10;
16 | }
17 | if (x == 1) {
18 | return n - y + 1 + countDigitOne(y - 1) + countDigitOne(n % y);
19 | } else {
20 | return y + x * countDigitOne(y - 1) + countDigitOne(n % y);
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/PalindromePartitioningII.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.Arrays;
4 |
5 | public class PalindromePartitioningII {
6 |
7 | public int minCut(String s) {
8 | if (s == null || s.isEmpty() || s.length() == 1) {
9 | return 0;
10 | }
11 |
12 | // t[i][j] = true iff s[i:j] is palindrome
13 | boolean[][] palindromeTable = new boolean[s.length()][s.length()];
14 | for (int j = 0; j < s.length(); j++) {
15 | palindromeTable[j][j] = true;
16 | for (int i = j - 1; i >= 0; i--) {
17 | if (s.charAt(i) == s.charAt(j)) {
18 | if (i == j - 1) {
19 | palindromeTable[i][j] = true;
20 | } else {
21 | palindromeTable[i][j] = palindromeTable[i + 1][j - 1];
22 | }
23 | } else {
24 | palindromeTable[i][j] = false;
25 | }
26 | }
27 | }
28 |
29 | int[] minCuts = new int[s.length()];
30 | Arrays.fill(minCuts, 0);
31 | for (int i = 0; i < s.length(); i++) {
32 | if (palindromeTable[0][i]) {
33 | minCuts[i] = 0;
34 | } else {
35 | int minCut = i;
36 | for (int j = 0; j < i; j++) {
37 | if (palindromeTable[j + 1][i]) {
38 | if (minCut > minCuts[j] + 1) {
39 | minCut = minCuts[j] + 1;
40 | }
41 | }
42 | }
43 | minCuts[i] = minCut;
44 | }
45 | }
46 | return minCuts[s.length()-1];
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/PartitionList.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Given a linked list and a value x, partition it such that all nodes less
7 | * than x come before nodes greater than or equal to x.
8 | *
9 | * You should preserve the original relative order of the nodes in each of the
10 | * two partitions.
11 | *
12 | * For example,
13 | *
14 | * Given 1->4->3->2->5->2 and x = 3,
15 | *
16 | * return 1->2->2->4->3->5.
17 | */
18 | public class PartitionList {
19 |
20 | public ListNode partition(ListNode head, int x) {
21 | if (head == null || head.next == null) {
22 | return head;
23 | }
24 |
25 | ListNode head1 = new ListNode(0);
26 | ListNode head2 = new ListNode(0);
27 |
28 | ListNode p = head1;
29 | ListNode q = head2;
30 | while (head != null) {
31 | if (head.val < x) {
32 | p.next = head;
33 | p = head;
34 | } else {
35 | q.next = head;
36 | q = head;
37 | }
38 | head = head.next;
39 | }
40 | p.next = head2.next;
41 | q.next = null;
42 | return head1.next;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/PascalsTriangle.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.List;
6 |
7 | /**
8 | * Given numRows, generate the first numRows of Pascal's triangle.
9 | */
10 | public class PascalsTriangle {
11 |
12 | public List
9 | * For example, given k = 3, Return [1,3,3,1].
10 | *
11 | * Note: Could you optimize your algorithm to use only O(k) extra space?
12 | */
13 | public class PascalsTriangle2 {
14 |
15 | public List
9 | * By listing and labeling all of the permutations in order, We get the
10 | * following sequence (ie, for n = 3):
11 | *
12 | * "123" "132" "213" "231" "312" "321"
13 | *
14 | * Given n and k, return the kth permutation sequence.
15 | *
16 | * Note: Given n will be between 1 and 9 inclusive.
17 | */
18 | public class PermutationSequence {
19 |
20 | public String getPermutation(int n, int k) {
21 | long f = factorial(n);
22 | if (k < 1 || k > f) {
23 | throw new IllegalArgumentException();
24 | }
25 | k--;
26 | f /= n;
27 | List
7 | * The digits are stored such that the most significant digit is at the head of
8 | * the list.
9 | */
10 | public class PlusOne {
11 |
12 | public int[] plusOne(int[] digits) {
13 | if (digits == null || digits.length == 0) {
14 | return digits;
15 | }
16 | int carry = 1;
17 | int i = digits.length - 1;
18 | while (carry != 0 && i >= 0) {
19 | digits[i] += carry;
20 | if (digits[i] < 10) {
21 | carry = 0;
22 | break;
23 | }
24 | digits[i] %= 10;
25 | i--;
26 | }
27 | // add one digit
28 | if (carry == 1) {
29 | int tmp[] = new int[digits.length + 1];
30 | System.arraycopy(digits, 0, tmp, 1, digits.length);
31 | tmp[0] = 1;
32 | digits = tmp;
33 | }
34 | return digits;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/PowXN.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.HashMap;
4 |
5 | /**
6 | * Implement pow(x, n).
7 | */
8 | public class PowXN {
9 |
10 | public double pow(double x, int n) {
11 | if (n == 0) {
12 | return 1;
13 | } else if (n > 0) {
14 | return pow(x, n, new HashMap
7 | * Solve it without division and in O(n).
8 | *
9 | * For example, given [1,2,3,4], return [24,12,8,6].
10 | */
11 | public class ProductOfArrayExceptSelf {
12 | public int[] productExceptSelf(int[] nums) {
13 | int[] p = new int[nums.length];
14 |
15 | int product = 1;
16 | for (int i = 0; i < p.length; ++i) {
17 | p[i] = product;
18 | product *= nums[i];
19 | }
20 |
21 | product = 1;
22 | for (int i = p.length - 1; i >= 0; --i) {
23 | p[i] *= product;
24 | product *= nums[i];
25 | }
26 | return p;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RangeSumQueryImmutable.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j),
5 | * inclusive.
6 | *
7 | * Example:
8 | * Given nums = [-2, 0, 3, -5, 2, -1]
9 | *
8 | * Each
letter
in
the
magazine
string
can
only
be
used
once
in
your
ransom
note.
9 | *
10 | * Note:
11 | * You may assume that both strings contain only lowercase letters.
12 | *
6 | * Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
7 | */
8 | public class RectangleArea {
9 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
10 | int a1 = area(C - A, D - B);
11 | int a2 = area(G - E, H - F);
12 | int intersection = getIntersection(A, B, C, D, E, F, G, H);
13 | return a1 + a2 - intersection;
14 | }
15 |
16 | private int getIntersection(int a, int b, int c, int d, int e, int f, int g, int h) {
17 | int width = 0;
18 | if (isIntersected(a, c, e, g)) {
19 | width = Math.min(c, g) - Math.max(a, e);
20 | }
21 | int height = 0;
22 | if (isIntersected(b, d, f, h)) {
23 | height = Math.min(d, h) - Math.max(b, f);
24 | }
25 | return area(width, height);
26 | }
27 |
28 | private boolean isIntersected(int a, int b, int c, int d) {
29 | return (a <= c && c <= b) || (a <= d && d <= b)
30 | || (c <= a && a <= d) || (c <= b && b <= d);
31 | }
32 |
33 | private int area(int width, int height) {
34 | return width * height;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RemoveDuplicatesFromSortedArray.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given a sorted array, remove the duplicates in place such that each element
5 | * appear only once and return the new length.
6 | *
7 | * Do not allocate extra space for another array, you must do this in place
8 | * with constant memory.
9 | *
10 | * For example, Given input array A = [1,1,2],
11 | *
12 | * Your function should return length = 2, and A is now [1,2].
13 | */
14 | public class RemoveDuplicatesFromSortedArray {
15 |
16 | public int removeDuplicates(int[] A) {
17 | if (A == null || A.length == 0) {
18 | return 0;
19 | }
20 | int length = 1;
21 | for (int i = 1; i < A.length; i++) {
22 | if (A[i] != A[i - 1]) {
23 | A[length] = A[i];
24 | length++;
25 | }
26 | }
27 | return length;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RemoveDuplicatesFromSortedArrayII.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Follow up for "Remove Duplicates": What if duplicates are allowed at most
5 | * twice?
6 | *
7 | * For example, Given sorted array A = [1,1,1,2,2,3],
8 | *
9 | * Your function should return length = 5, and A is now [1,1,2,2,3].
10 | */
11 | public class RemoveDuplicatesFromSortedArrayII {
12 |
13 | public int removeDuplicates(int[] A) {
14 | if (A == null || A.length == 0) {
15 | return 0;
16 | }
17 | int length = 1;
18 | int count = 1;
19 | for (int i = 1; i < A.length; i++) {
20 | if (A[i] != A[i - 1]) {
21 | count = 1;
22 | A[length] = A[i];
23 | length++;
24 | } else if (count < 2) {
25 | count++;
26 | A[length] = A[i];
27 | length++;
28 | }
29 | }
30 | return length;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RemoveDuplicatesFromSortedList.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Given a sorted linked list, delete all duplicates such that each element
7 | * appear only once.
8 | *
9 | * For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return
10 | * 1->2->3.
11 | */
12 | public class RemoveDuplicatesFromSortedList {
13 |
14 | public ListNode deleteDuplicates(ListNode head) {
15 | if (head == null) {
16 | return head;
17 | }
18 | ListNode cur = head;
19 | while (cur != null) {
20 | // contains;
21 | ListNode tmp = cur;
22 | while (tmp.next != null) {
23 | if (tmp.next.val == cur.val) {
24 | tmp.next = tmp.next.next;
25 | } else {
26 | tmp = tmp.next;
27 | }
28 | }
29 | cur = cur.next;
30 | }
31 | return head;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RemoveDuplicatesFromSortedListII.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Given a sorted linked list, delete all nodes that have duplicate numbers,
7 | * leaving only distinct numbers from the original list.
8 | *
9 | * For example,
10 | *
11 | * Given 1->2->3->3->4->4->5, return 1->2->5.
12 | *
13 | * Given 1->1->1->2->3, return 2->3.
14 | */
15 | public class RemoveDuplicatesFromSortedListII {
16 |
17 | public ListNode deleteDuplicates(ListNode head) {
18 | if (head == null || head.next == null) {
19 | return head;
20 | }
21 | // fake head
22 | ListNode p = new ListNode(0);
23 | p.next = head;
24 | head = p;
25 |
26 | p = head;
27 | while (p.next != null) {
28 | ListNode next = p.next;
29 | while (next.next != null && next.val == next.next.val) {
30 | next = next.next;
31 | }
32 | if (p.next == next) {
33 | p = p.next;
34 | } else {
35 | p.next = next.next;
36 | }
37 | }
38 | return head.next;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RemoveElement.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given an array and a value, remove all instances of that value in place and
5 | * return the new length.
6 | *
7 | * The order of elements can be changed. It doesn't matter what you leave
8 | * beyond the new length.
9 | */
10 | public class RemoveElement {
11 |
12 | public int removeElement(int[] A, int elem) {
13 | if (A == null || A.length == 0) {
14 | return 0;
15 | }
16 | int length = 0;
17 | for(int i=0 ;i
8 | * Example2: x = -123, return -321
9 | *
10 | * Have you thought about this?
11 | *
12 | * Here are some good questions to ask before coding. Bonus points for you if
13 | * you have already thought through this!
14 | *
15 | * If the integer's last digit is 0, what should the output be? ie, cases such
16 | * as 10, 100.
17 | *
18 | * Did you notice that the reversed integer might overflow? Assume the input is
19 | * a 32-bit integer, then the reverse of 1000000003 overflows. How should you
20 | * handle such cases?
21 | *
22 | * Throw an exception? Good, but what if throwing an exception is not an
23 | * option? You would then have to re-design the function (ie, add an extra
24 | * parameter).
25 | */
26 | public class ReverseInteger {
27 |
28 | public int reverse(int x) {
29 | boolean neg = x < 0 ? true : false;
30 | if (neg) {
31 | x = -1 * x;
32 | }
33 | int rev = 0;
34 | while (x > 0) {
35 | int d = x % 10;
36 | rev = 10 * rev + d;
37 | x /= 10;
38 | }
39 | if (neg) {
40 | rev = -1 * rev;
41 | if (rev >= 0) {
42 | // overflow
43 | throw new RuntimeException("overflow");
44 | }
45 | } else {
46 | if (rev < 0) {
47 | // overflow
48 | throw new RuntimeException("overflow");
49 | }
50 | }
51 | return rev;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ReverseLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Reverse a singly linked list.
7 | */
8 | public class ReverseLinkedList {
9 | public ListNode reverseList(ListNode head) {
10 | if (head == null) {
11 | return head;
12 | }
13 | ListNode p = head;
14 | ListNode q = p.next;
15 | while (q != null) {
16 | ListNode r = q.next;
17 | q.next = p;
18 | p = q;
19 | q = r;
20 | }
21 | head.next = null;
22 | return p;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ReverseString.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Write a function that takes a string as input and returns the string reversed.
5 | *
6 | * Example:
7 | * Given s = "hello", return "olleh".
8 | */
9 | public class ReverseString {
10 | public String reverseString(String s) {
11 | if (s == null || s.isEmpty()) {
12 | return s;
13 | }
14 | return new StringBuilder(s).reverse().toString();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ReverseVowelsOfAString.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Write a function that takes a string as input and reverse only the vowels of a string.
5 | *
6 | * Example 1:
7 | *
8 | * Given s = "hello", return "holle".
9 | *
10 | * Example 2:
11 | *
12 | * Given s = "leetcode", return "leotcede".
13 | */
14 | public class ReverseVowelsOfAString {
15 | public String reverseVowels(String s) {
16 | if (s == null || s.isEmpty()) {
17 | return s;
18 | }
19 | char [] cs = s.toCharArray();
20 | int i = 0;
21 | int j = cs.length - 1;
22 | while (i < j) {
23 | while (i < cs.length && !isVowel(cs[i])) {
24 | i ++;
25 | }
26 | while (j >= 0 && !isVowel(cs[j])) {
27 | j--;
28 | }
29 | if (i < j) {
30 | swap(cs, i, j);
31 | i ++;
32 | j --;
33 | }
34 | }
35 | return new String(cs);
36 | }
37 |
38 | private boolean isVowel(char c) {
39 | return c == 'a' || c == 'e' ||c == 'i' ||c == 'o' ||c == 'u'
40 | || c == 'A' || c == 'E' ||c == 'I' ||c == 'O' ||c == 'U';
41 | }
42 |
43 | private void swap (char [] cs, int i, int j) {
44 | char c = cs[i];
45 | cs[i] = cs[j];
46 | cs[j] = c;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ReverseWordsInAString.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * Given an input string, reverse the string word by word.
7 | */
8 | public class ReverseWordsInAString {
9 |
10 | public String reverseWords(String s) {
11 | if (s == null) {
12 | return null;
13 | }
14 | if (s.length() == 0) {
15 | return "";
16 | }
17 | int state = 0;
18 | int start = -1;
19 | Stack
6 | * For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
7 | */
8 | public class RotateArray {
9 | public void rotate(int[] nums, int k) {
10 | if (nums == null || nums.length == 0) {
11 | return;
12 | }
13 | k = k % nums.length;
14 |
15 | int[] copy = new int[nums.length];
16 | int i = 0;
17 | int j = nums.length - k;
18 | while (j < nums.length) {
19 | copy[i] = nums[j];
20 | i++;
21 | j++;
22 | }
23 |
24 | j = 0;
25 | while (j < nums.length - k) {
26 | copy[i] = nums[j];
27 | i++;
28 | j++;
29 | }
30 |
31 | for (i = 0; i < nums.length; i++) {
32 | nums[i] = copy[i];
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RotateImage.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * You are given an n x n 2D matrix representing an image.
5 | *
6 | * Rotate the image by 90 degrees (clockwise).
7 | *
8 | * Follow up: Could you do this in-place?
9 | */
10 | public class RotateImage {
11 |
12 | public void rotate(int[][] matrix) {
13 | if (matrix == null || matrix.length == 0) {
14 | return;
15 | }
16 | for (int layer = 0; layer < matrix.length / 2; layer++) {
17 | // [start, end]
18 | int start = layer;
19 | int end = matrix.length - layer - 1;
20 | for (int i = start; i < end; i++) {
21 | int tmp = matrix[layer][i];
22 | // left --> top
23 | matrix[layer][i] = matrix[matrix.length - 1 - i][layer];
24 | // bottom --> left
25 | matrix[matrix.length - 1 - i][layer] =
26 | matrix[matrix.length - 1 - layer][matrix.length - 1 - i];
27 | // right --> bottom
28 | matrix[matrix.length - 1 - layer][matrix.length - 1 - i] =
29 | matrix[i][matrix.length - 1 - layer];
30 | // top --> right
31 | matrix[i][matrix.length - 1 - layer] =
32 | tmp;
33 | }
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RotateList.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Given a list, rotate the list to the right by k places, where k is
7 | * non-negative.
8 | *
9 | * For example: Given 1->2->3->4->5->NULL and k = 2, return
10 | * 4->5->1->2->3->NULL.
11 | */
12 | public class RotateList {
13 |
14 | public ListNode rotateRight(ListNode head, int n) {
15 | if (head == null) {
16 | return null;
17 | }
18 | int length = 1;
19 | ListNode p = head;
20 | while(p.next != null) {
21 | p = p.next;
22 | length ++;
23 | }
24 | n = n % length;
25 | // find the nth from last;
26 | p = head;
27 | for (int i = 0; i < n; i++) {
28 | p = p.next;
29 | if (p == null) {
30 | return null;
31 | }
32 | }
33 | ListNode newHead = head;
34 | while (p.next != null) {
35 | newHead = newHead.next;
36 | p = p.next;
37 | }
38 | p.next = head;
39 | p = newHead;
40 | newHead = newHead.next;
41 | p.next = null;
42 | return newHead;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SameTree.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.TreeNode;
4 |
5 | /**
6 | * Given two binary trees, write a function to check if they are equal or not.
7 | *
8 | * Two binary trees are considered equal if they are structurally identical and
9 | * the nodes have the same value.
10 | */
11 | public class SameTree {
12 |
13 | public boolean isSameTree(TreeNode p, TreeNode q) {
14 | if (p == null && q == null) {
15 | return true;
16 | } else if (p == null || q == null) {
17 | return false;
18 | } else if (p.val != q.val) {
19 | return false;
20 | } else if (!isSameTree(p.left, q.left)) {
21 | return false;
22 | } else {
23 | return isSameTree(p.right, q.right);
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SearchA2DMatrix.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Write an efficient algorithm that searches for a value in an m x n matrix.
5 | * This matrix has the following properties:
6 | *
7 | * Integers in each row are sorted from left to right. The first integer of
8 | * each row is greater than the last integer of the previous row. For example,
9 | *
10 | * Consider the following matrix:
11 | *
12 | *
7 | * Integers in each row are sorted in ascending from left to right.
8 | * Integers in each column are sorted in ascending from top to bottom.
9 | *
10 | * For example,
11 | *
12 | * Consider the following matrix:
13 | *
24 | * Given target = 20, return false.
25 | */
26 | public class SearchA2DMatrix2 {
27 | public boolean searchMatrix(int[][] matrix, int target) {
28 | if (matrix == null) {
29 | return false;
30 | }
31 | return searchMatrixHelper(matrix, target, 0, matrix[0].length - 1);
32 | }
33 |
34 | private boolean searchMatrixHelper(int[][] matrix, int target, int row, int col) {
35 | if (row == matrix.length) {
36 | return false;
37 | }
38 | if (col < 0) {
39 | return false;
40 | }
41 | if (matrix[row][col] == target) {
42 | return true;
43 | }
44 | if (matrix[row][col] > target) {
45 | return searchMatrixHelper(matrix, target, row, col - 1);
46 | }
47 | return searchMatrixHelper(matrix, target, row + 1, col);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SearchInsertPosition.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given a sorted array and a target value, return the index if the target is
5 | * found. If not, return the index where it would be if it were inserted in
6 | * order.
7 | *
8 | * You may assume no duplicates in the array.
9 | *
10 | * Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4
11 | * [1,3,5,6], 0 → 0
12 | */
13 | public class SearchInsertPosition {
14 |
15 | public int searchInsert(int[] A, int target) {
16 | if (A == null) {
17 | throw new NullPointerException();
18 | }
19 | if (A.length == 0) {
20 | return 0;
21 | }
22 | return searchInsertHelper(A, target, 0, A.length);
23 | }
24 |
25 | private int searchInsertHelper(int[] A, int target, int start, int end) {
26 | if (start == end) {
27 | return start;
28 | }
29 | int mid = (start + end) / 2;
30 | if (A[mid] == target) {
31 | return mid;
32 | } else if (A[mid] < target) {
33 | return searchInsertHelper(A, target, mid + 1, end);
34 | } else {
35 | return searchInsertHelper(A, target, start, mid);
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ShortestPalindrome.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given a string S, you are allowed to convert it to a palindrome by adding characters in front of
5 | * it. Find and return the shortest palindrome you can find by performing this transformation.
6 | *
7 | * For example:
8 | *
9 | * Given "aacecaaa", return "aaacecaaa".
10 | *
11 | * Given "abcd", return "dcbabcd".
12 | */
13 | public class ShortestPalindrome {
14 | public String shortestPalindrome(String s) {
15 | if (s == null || s.isEmpty()) {
16 | return s;
17 | }
18 | char[] chars = s.toCharArray();
19 | for (int i = chars.length - 1; i >= 1; i--) {
20 | if (isPalindrome(chars, i)) {
21 | return reverse(s.substring(i + 1)) + s;
22 | }
23 | }
24 | return reverse(s.substring(1)) + s;
25 | }
26 |
27 | private String reverse(String s) {
28 | return new StringBuilder(s).reverse().toString();
29 | }
30 |
31 | private boolean isPalindrome(char[] chars, int end) {
32 | for (int i = 0; i < (end + 1) / 2; i++) {
33 | if (chars[i] != chars[end - i]) {
34 | return false;
35 | }
36 | }
37 | return true;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SingleNumber.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given an array of integers, every element appears twice except for one. Find
5 | * that single one.
6 | *
7 | * Note: Your algorithm should have a linear runtime complexity. Could you
8 | * implement it without using extra memory?
9 | */
10 | public class SingleNumber {
11 | public int singleNumber(int[] A) {
12 | for(int i=1; i
7 | * For example:
8 | *
9 | * Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
10 | *
11 | * Note:
12 | * The order of the result is not important. So in the above example, [5, 3] is also correct.
13 | * Your algorithm should run in linear runtime complexity. Could you implement it using only
14 | * constant space complexity?
15 | */
16 | public class SingleNumberIII {
17 | /**
18 | * Find the rightmost set bit, divide numbers into two groups. Each group will end up being one
19 | * unique number.
20 | */
21 | public int[] singleNumber(int[] nums) {
22 | int xor = nums[0];
23 | for (int i = 1; i < nums.length; i++) {
24 | xor ^= nums[i];
25 | }
26 |
27 | int bit = xor & ~(xor - 1);
28 | int num1 = 0;
29 | int num2 = 0;
30 |
31 | for (int num : nums) {
32 | if ((num & bit) > 0) {
33 | num1 ^= num;
34 | } else {
35 | num2 ^= num;
36 | }
37 | }
38 | return new int[]{num1, num2};
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SpiralMatrixII.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given an integer n, generate a square matrix filled with elements from 1 to
5 | * n2 in spiral order.
6 | *
7 | * For example,
8 | *
9 | * Given n = 3,
10 | *
11 | * You should return the following matrix:
12 | *
13 | *
8 | * Example:
9 | *
9 | * An example is the root-to-leaf path 1->2->3 which represents the number 123.
10 | *
11 | * Find the total sum of all root-to-leaf numbers.
12 | *
13 | * For example,
14 | *
15 | *
24 | * Return the sum = 12 + 13 = 25.
25 | */
26 | public class SumRootToLeafNumbers {
27 |
28 | public int sumNumbers(TreeNode root) {
29 | if (root == null) {
30 | return 0;
31 | }
32 | return sumNumbersHelper(root, 0, 0);
33 | }
34 |
35 | private int sumNumbersHelper(TreeNode root, int sum, int num) {
36 | // leaf
37 | if (root.left == null && root.right == null) {
38 | return sum + num + root.val;
39 | }
40 | num += root.val;
41 | if (root.left != null) {
42 | sum = sumNumbersHelper(root.left, sum, num * 10);
43 | }
44 | if (root.right != null) {
45 | sum = sumNumbersHelper(root.right, sum, num * 10);
46 | }
47 | return sum;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SwapNodesInPairs.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 |
5 | /**
6 | * Given a linked list, swap every two adjacent nodes and return its head.
7 | *
8 | * For example,
9 | *
10 | * Given 1->2->3->4, you should return the list as 2->1->4->3.
11 | *
12 | * Your algorithm should use only constant space. You may not modify the values
13 | * in the list, only nodes itself can be changed.
14 | */
15 | public class SwapNodesInPairs {
16 |
17 | public ListNode swapPairs(ListNode head) {
18 | if (head == null || head.next == null) {
19 | return head;
20 | }
21 | ListNode p = new ListNode(0);
22 | p.next = head;
23 | head = p;
24 | while(p.next != null && p.next.next != null) {
25 | ListNode a = p.next;
26 | ListNode b = a.next;
27 | ListNode c = b.next;
28 | p.next = b;
29 | b.next = a;
30 | a.next = c;
31 | p = a;
32 | }
33 | return head.next;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SymmetricTree.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.TreeNode;
4 |
5 | /**
6 | * Given a binary tree, check whether it is a mirror of itself (ie, symmetric
7 | * around its center).
8 | *
9 | * For example, this binary tree is symmetric:
10 | *
11 | *
31 | * Bonus points if you could solve it both recursively and iteratively.
32 | */
33 | public class SymmetricTree {
34 |
35 | public boolean isSymmetric(TreeNode root) {
36 | if (root == null) {
37 | return true;
38 | }
39 | return isSymmetricHelper(root.left, root.right);
40 | }
41 |
42 | private boolean isSymmetricHelper(TreeNode node1, TreeNode node2) {
43 | if (node1 == null && node2 == null) {
44 | return true;
45 | } else if (node1 == null) {
46 | return false;
47 | } else if (node2 == null) {
48 | return false;
49 | } else if (node1.val != node2.val) {
50 | return false;
51 | } else {
52 | return isSymmetricHelper(node1.left, node2.right)
53 | && isSymmetricHelper(node1.right, node2.left);
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ThreeSumClosest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Given an array S of n integers, find three integers in S such that the sum is closest to a given
7 | * number, target. Return the sum of the three integers. You may assume that each input would have
8 | * exactly one solution.
9 | *
12 | * For example,
13 | * Given [1,1,1,2,2,3] and k = 2, return [1,2].
14 | *
15 | * Note:
16 | *
6 | * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are
7 | * ugly while 14 is not ugly since it includes another prime factor 7.
8 | *
9 | * Note that 1 is typically treated as an ugly number.
10 | */
11 | public class UglyNumber {
12 | public boolean isUgly(int num) {
13 | if (num == 0) {
14 | return false;
15 | }
16 | if (num == 1) {
17 | return true;
18 | }
19 | int r = num % 2;
20 | while (r == 0) {
21 | num = num / 2;
22 | r = num % 2;
23 | }
24 | r = num % 3;
25 | while (r == 0) {
26 | num = num / 3;
27 | r = num % 3;
28 | }
29 | r = num % 5;
30 | while (r == 0) {
31 | num = num / 5;
32 | r = num % 5;
33 | }
34 | return num == 1;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/UniqueBinarySearchTrees.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given n, how many structurally unique BST's (binary search trees) that store
5 | * values 1...n?
6 | *
7 | * For example,
8 | *
9 | * Given n = 3, there are a total of 5 unique BST's.
10 | *
11 | *
7 | * The robot can only move either down or right at any point in time. The robot
8 | * is trying to reach the bottom-right corner of the grid (marked 'Finish' in
9 | * the diagram below).
10 | *
11 | * How many possible unique paths are there?
12 | *
13 | * Note: m and n will be at most 100.
14 | */
15 | public class UniquePaths {
16 |
17 | public int uniquePaths(int m, int n) {
18 | int[][] table = new int[m][n];
19 | for (int i = 0; i < m; i++) {
20 | table[i][0] = 1;
21 | }
22 | for (int j = 0; j < n; j++) {
23 | table[0][j] = 1;
24 | }
25 | for (int i = 1; i < m; i++) {
26 | for (int j = 1; j < n; j++) {
27 | table[i][j] = table[i - 1][j] + table[i][j - 1];
28 | }
29 | }
30 | return table[m - 1][n - 1];
31 | }
32 |
33 | }
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ValidAnagram.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given two strings s and t, write a function to determine if t is an anagram of s.
5 | *
6 | * For example,
7 | *
8 | * s = "anagram", t = "nagaram", return true.
9 | *
10 | * s = "rat", t = "car", return false.
11 | */
12 | public class ValidAnagram {
13 | public boolean isAnagram(String s, String t) {
14 | if (s == null && t == null) {
15 | return true;
16 | }
17 | if (s == null || t == null) {
18 | return false;
19 | }
20 | int[] alphabet = new int[26];
21 | for (char c : s.toCharArray()) {
22 | alphabet[c - 'a']++;
23 | }
24 | for (char c : t.toCharArray()) {
25 | alphabet[c - 'a']--;
26 | }
27 | for (int i : alphabet) {
28 | if (i != 0) {
29 | return false;
30 | }
31 | }
32 | return true;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ValidParentheses.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * Given a string containing just the characters '(', ')', '{', '}', '[' and
7 | * ']', determine if the input string is valid.
8 | *
9 | * The brackets must close in the correct order, "()" and "()[]{}" are all
10 | * valid but "(]" and "([)]" are not.
11 | */
12 | public class ValidParentheses {
13 |
14 | public boolean isValid(String s) {
15 | if (s == null || s.isEmpty()) {
16 | return true;
17 | }
18 | Stack
8 | * Note:
9 | * You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
10 | */
11 | public class KthSmallestElementInABST {
12 | public int kthSmallest(TreeNode root, int k) {
13 | if (root == null || k == -1) {
14 | return -1;
15 | }
16 | return kthSmallestHelper(root, k)[1];
17 | }
18 |
19 | //
7 | * For example,
8 | * Given nums = [0, 1, 3] return 2.
9 | *
10 | * Note:
11 | * Your algorithm should run in linear runtime complexity. Could you implement it using only
12 | * constant extra space complexity?
13 | */
14 | public class MissingNumber {
15 | public int missingNumber(int[] nums) {
16 | if (nums == null || nums.length == 0) {
17 | return 0;
18 | }
19 | int actual = 0;
20 | for (int i : nums) {
21 | actual += i;
22 | }
23 | int expected = nums.length * (nums.length + 1) / 2;
24 | return expected - actual;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/MissingNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | public class MissingNumberTest {
8 |
9 | MissingNumber t = new MissingNumber();
10 |
11 | @Test
12 | public void testMissingNumber() throws Exception {
13 | assertEquals(2, t.missingNumber(new int[]{0, 1, 3}));
14 | }
15 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/NumberOfDigitOneTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | public class NumberOfDigitOneTest {
8 |
9 | NumberOfDigitOne t = new NumberOfDigitOne();
10 |
11 | @Test
12 | public void testCountDigitOne() throws Exception {
13 | assertEquals(6, t.countDigitOne(13));
14 | }
15 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/OddEvenLinkedListTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 | import org.junit.Test;
5 |
6 | import static org.junit.Assert.*;
7 |
8 | public class OddEvenLinkedListTest {
9 |
10 | private OddEvenLinkedList t = new OddEvenLinkedList();
11 |
12 | @Test
13 | public void testOddEvenList() throws Exception {
14 | ListNode a = ListNode.createList(new int[]{1,2,3,4,5});
15 | System.out.println(t.oddEvenList(a));
16 | }
17 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/PalindromePartitioningIITest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | /**
8 | * Given a string s, partition s such that every substring of the partition is
9 | * a palindrome.
10 | *
11 | * Return the minimum cuts needed for a palindrome partitioning of s.
12 | *
13 | * For example, given s = "aab", Return 1 since the palindrome partitioning
14 | * ["aa","b"] could be produced using 1 cut.
15 | */
16 | public class PalindromePartitioningIITest {
17 |
18 | PalindromePartitioningII s = new PalindromePartitioningII();
19 |
20 | @Test
21 | public void testMinCut() {
22 | assertEquals(1, s.minCut("aab"));
23 | assertEquals(2, s.minCut("leet"));
24 | assertEquals(1, s.minCut("ab"));
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/PartitionListTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | import com.pengyifan.leetcode.commons.ListNode;
8 |
9 | public class PartitionListTest {
10 |
11 | PartitionList s = new PartitionList();
12 |
13 | @Test
14 | public void testPartition() {
15 | ListNode head = ListNode.createList(new int[] { 2, 1 });
16 | head = s.partition(head, 2);
17 | assertEquals(1, head.val);
18 | head = head.next;
19 | assertEquals(2, head.val);
20 | head = head.next;
21 | assertNull(head);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/PascalsTriangle2Test.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import java.util.Arrays;
6 |
7 | import org.junit.Test;
8 |
9 | public class PascalsTriangle2Test {
10 |
11 | PascalsTriangle2 t = new PascalsTriangle2();
12 |
13 | @Test
14 | public void test() {
15 | assertEquals(Arrays.asList(1, 3, 3, 1), t.getRow(3));
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/PascalsTriangleTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.hamcrest.CoreMatchers.hasItem;
4 | import static org.junit.Assert.assertThat;
5 |
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import org.junit.Test;
10 |
11 | public class PascalsTriangleTest {
12 |
13 | PascalsTriangle t = new PascalsTriangle();
14 |
15 | @Test
16 | public void testGenerate() {
17 | List
10 | * Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
11 | *
12 | * Return: 1 --> 2 --> 3 --> 4 --> 5
13 | */
14 | public class RemoveLinkedListElements {
15 | public ListNode removeElements(ListNode head, int val) {
16 | return removeHelper(head, val);
17 | }
18 |
19 | private ListNode removeHelper(ListNode head, int val) {
20 | if (head == null) {
21 | return null;
22 | } else if (head.val == val) {
23 | return removeHelper(head.next, val);
24 | } else {
25 | head.next = removeHelper(head.next, val);
26 | return head;
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/RemoveLinkedListElementsTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 | import org.junit.Test;
5 |
6 | import static org.junit.Assert.assertEquals;
7 |
8 | public class RemoveLinkedListElementsTest {
9 |
10 | private RemoveLinkedListElements t = new RemoveLinkedListElements();
11 |
12 | @Test
13 | public void testRemoveElements() throws Exception {
14 | ListNode l1 = ListNode.createList(new int[]{1, 2, 6, 3, 4, 5, 6});
15 | l1 = t.removeElements(l1, 6);
16 | assertEquals("1 --> 2 --> 3 --> 4 --> 5", l1.toString());
17 |
18 | l1 = ListNode.createList(new int[]{1, 1});
19 | l1 = t.removeElements(l1, 1);
20 | assertEquals(null, l1);
21 | }
22 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/RestoreIpAddressesTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.hamcrest.CoreMatchers.hasItem;
4 | import static org.junit.Assert.assertEquals;
5 | import static org.junit.Assert.assertThat;
6 |
7 | import java.util.List;
8 |
9 | import org.junit.Test;
10 |
11 | public class RestoreIpAddressesTest {
12 |
13 | RestoreIpAddresses t = new RestoreIpAddresses();
14 |
15 | @Test
16 | public void test() {
17 | List
12 | *
15 | * What is the minimum candies you must give?
16 | */
17 | public class Candy {
18 |
19 | public int candy(int[] ratings) {
20 |
21 | int[] scanLeft = new int[ratings.length];
22 | Arrays.fill(scanLeft, 1);
23 | for (int i = 1; i < ratings.length; i++) {
24 | if (ratings[i] > ratings[i - 1]) {
25 | scanLeft[i] = scanLeft[i - 1] + 1;
26 | }
27 | }
28 |
29 | int[] scanRight = new int[ratings.length];
30 | Arrays.fill(scanRight, 1);
31 | for (int i = ratings.length - 2; i >= 0; i--) {
32 | if (ratings[i] > ratings[i + 1]) {
33 | scanRight[i] = scanRight[i + 1] + 1;
34 | }
35 | }
36 |
37 | int sum = 0;
38 | for (int i = 0; i < ratings.length; i++) {
39 | sum += Math.max(scanLeft[i], scanRight[i]);
40 | }
41 | return sum;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ClimbingStairs.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * You are climbing a stair case. It takes n steps to reach to the top.
5 | * > findAll(int[] array) {
10 | if (array == null || array.length == 0) {
11 | return Collections.emptyList();
12 | }
13 |
14 | List
> solutions = new ArrayList
>();
15 | int target = 0;
16 | while (target < array.length) {
17 | int end = binarySearch(array, target, target, array.length - 1);
18 | List
11 | *
15 | */
16 | public class EditDistance {
17 |
18 | public int minDistance(String word1, String word2) {
19 | if (word1 == null || word2 == null) {
20 | return 0;
21 | }
22 | int[][] table = new int[word1.length() + 1][word2.length() + 1];
23 | for (int i = 0; i < table.length; i++) {
24 | Arrays.fill(table[i], 0);
25 | }
26 |
27 | for (int i = 0; i <= word1.length(); i++) {
28 | table[i][0] = i;
29 | }
30 | for (int i = 0; i <= word2.length(); i++) {
31 | table[0][i] = i;
32 | }
33 | for (int i = 1; i <= word1.length(); i++) {
34 | for (int j = 1; j <= word2.length(); j++) {
35 | table[i][j] = Math.min(table[i - 1][j] + 1, table[i][j - 1] + 1);
36 | if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
37 | table[i][j] = Math.min(table[i][j], table[i - 1][j - 1]);
38 | } else {
39 | table[i][j] = Math.min(table[i][j], table[i - 1][j - 1] + 1);
40 | }
41 | }
42 | }
43 | return table[word1.length()][word2.length()];
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ExcelSheetColumnNumber.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Related to question Excel Sheet Column Title
5 | *
10 | * A -> 1
11 | * B -> 2
12 | * C -> 3
13 | * ...
14 | * Z -> 26
15 | * AA -> 27
16 | * AB -> 28
17 | *
18 | */
19 | public class ExcelSheetColumnNumber {
20 | public int titleToNumber(String s) {
21 | if (s == null && s.length() == 0) {
22 | return 0;
23 | }
24 | int i = 0;
25 | for (char c : s.toCharArray()) {
26 | int n = c - 'A' + 1;
27 | i = i * 26 + n;
28 | }
29 | return i;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/ExcelSheetColumnTitle.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given a positive integer, return its corresponding column title as appear in an Excel sheet.
5 | *
8 | * 1 -> A
9 | * 2 -> B
10 | * 3 -> C
11 | * ...
12 | * 26 -> Z
13 | * 27 -> AA
14 | * 28 -> AB
15 | */
16 | public class ExcelSheetColumnTitle {
17 | public String convertToTitle(int n) {
18 | String s = "";
19 | while (n > 0) {
20 | n--;
21 | char ch = (char) (n % 26 + 'A');
22 | n /= 26;
23 | s = ch + s;
24 | }
25 | return s;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/FactorialTrailingZeroes.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Given an integer n, return the number of trailing zeroes in n!.
5 | *
13 | * Input:
14 | * s = "abcd"
15 | * t = "abcde"
16 | *
17 | * Output:
18 | * e
19 | *
20 | * Explanation:
21 | * 'e' is the letter that was added.
22 | */
23 | public class FindTheDifference {
24 | public char findTheDifference(String s, String t) {
25 | if (s == null) {
26 | return 0;
27 | }
28 | int[] countS = new int[26];
29 | for (char c : s.toCharArray()) {
30 | countS[c - 'a']++;
31 | }
32 | int[] countT = new int[26];
33 | for (char c : t.toCharArray()) {
34 | countT[c - 'a']++;
35 | }
36 | for (int i = 0; i < 26; i++) {
37 | if (countS[i] != countT[i]) {
38 | return (char) (i + 'a');
39 | }
40 | }
41 | return 0;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/FirstBadVersion.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * You are a product manager and currently leading a team to develop a new product. Unfortunately,
5 | * the latest version of your product fails the quality check. Since each version is developed
6 | * based
7 | * on the previous version, all the versions after a bad version are also bad.
8 | *
9 | * s = "leetcode"
10 | * return 0.
11 | *
12 | * s = "loveleetcode",
13 | * return 2.
14 | *
15 | * Note: You may assume the string contain only lowercase letters.
16 | */
17 | public class FirstUniqueCharacterInAString {
18 | public int firstUniqChar(String s) {
19 | if (s == null) {
20 | return -1;
21 | }
22 | int[] count = new int[256];
23 | for (char c : s.toCharArray()) {
24 | count[c]++;
25 | }
26 | for (int i = 0; i < s.length(); i++) {
27 | if (count[s.charAt(i)] < 2) {
28 | return i;
29 | }
30 | }
31 | return -1;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/GasStation.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * There are N gas stations along a circular route, where the amount of gas at
5 | * station i is gas[i].
6 | *
13 | * 1^2 + 9^2 = 82
14 | * 8^2 + 2^2 = 68
15 | * 6^2 + 8^2 = 100
16 | * 1^2 + 0^2 + 0^2 = 1
17 | */
18 | public class HappyNumber {
19 | public boolean isHappy(int n) {
20 | if (n == 1 || n == 7) {
21 | return true;
22 | } else if (n < 10) {
23 | return false;
24 | }
25 | return isHappy(getHappyNumber(n));
26 | }
27 |
28 | private int getHappyNumber(int n) {
29 | int i = 0;
30 | while (n > 0) {
31 | int x = n % 10;
32 | i += x * x;
33 | n /= 10;
34 | }
35 | return i;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/HouseRobber.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * You are a professional robber planning to rob houses along a street. Each house has a certain
5 | * amount of money stashed, the only constraint stopping you from robbing each of them is that
6 | * adjacent houses have security system connected and it will automatically contact the police if
7 | * two adjacent houses were broken into on the same night.
8 | *
14 | * Input:
15 | * "abccccdd"
16 | *
17 | * Output:
18 | * 7
19 | *
20 | * Explanation:
21 | * One longest palindrome that can be built is "dccaccd", whose length is 7.
22 | *
23 | */
24 | public class LongestPalindrome {
25 | public int longestPalindrome(String s) {
26 | if (s == null || s.isEmpty()) {
27 | return 0;
28 | }
29 | int[] count = new int[256];
30 | for (char c : s.toCharArray()) {
31 | count[c]++;
32 | }
33 | boolean hasOdd = false;
34 | int longest = 0;
35 | for (int c : count) {
36 | if (c % 2 == 0) {
37 | longest += c;
38 | } else {
39 | longest += c - 1;
40 | hasOdd = true;
41 | }
42 | }
43 | return longest + (hasOdd ? 1 : 0);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/LongestSubstringWithoutRepeatingCharacters.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Given a string, find the length of the longest substring without repeating characters.
8 | *
9 | *
14 | * Example:
15 | *
16 | * MinStack minStack = new MinStack();
17 | * minStack.push(-2);
18 | * minStack.push(0);
19 | * minStack.push(-3);
20 | * minStack.getMin(); --> Returns -3.
21 | * minStack.pop();
22 | * minStack.top(); --> Returns 0.
23 | * minStack.getMin(); --> Returns -2.
24 | *
25 | */
26 | public class MinStack {
27 |
28 | private Stack> generate(int numRows) {
13 | if (numRows <= 0) {
14 | return Collections.emptyList();
15 | }
16 | List
> lists = new ArrayList
>();
17 | List
12 | * 5
13 | * / \
14 | * 4 8
15 | * / / \
16 | * 11 13 4
17 | * / \ / \
18 | * 7 2 5 1
19 | *
20 | *
21 | * return
22 | *
23 | * [ [5,4,11,2], [5,8,4,5] ]
24 | */
25 | public class PathSum2 {
26 |
27 | public ArrayList
10 | * sumRange(0, 2) -> 1
11 | * sumRange(2, 5) -> -1
12 | * sumRange(0, 5) -> -3
13 | *
14 | * Note:
15 | * You may assume that the array does not change.
16 | * There are many calls to sumRange function.
17 | */
18 | public class RangeSumQueryImmutable {
19 |
20 | private int[] sum;
21 |
22 | public RangeSumQueryImmutable(int[] nums) {
23 | sum = new int[nums.length];
24 | if (nums.length > 0) {
25 | sum[0] = nums[0];
26 | for (int i = 1; i < nums.length; i++) {
27 | sum[i] = sum[i - 1] + nums[i];
28 | }
29 | }
30 | }
31 |
32 | public int sumRange(int i, int j) {
33 | if (i < 0 || i >= sum.length || j < 0 || j >= sum.length) {
34 | throw new Error();
35 | }
36 | if (i == 0) {
37 | return sum[j];
38 | } else {
39 | return sum[j] - sum[i - 1];
40 | }
41 | }
42 | }
43 |
44 | // Your RangeSumQueryImmutable object will be instantiated and called as such:
45 | // RangeSumQueryImmutable numArray = new RangeSumQueryImmutable(nums);
46 | // numArray.sumRange(0, 1);
47 | // numArray.sumRange(1, 2);
48 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RansomNote.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | *
Given
an
arbitrary
ransom
note
string
and
another
string
containing
letters from
all
5 | *
the
magazines,
write
a
function
that
will
return
true
if
the
ransom
note
can
be
6 | *
constructed
from
the
magazines ;
otherwise,
it
will
return
false.
7 | *
13 | * canConstruct("a", "b") -> false
14 | * canConstruct("aa", "ab") -> false
15 | * canConstruct("aa", "aab") -> true
16 | */
17 | public class RansomNote {
18 | public boolean canConstruct(String ransomNote, String magazine) {
19 | if (ransomNote == null && magazine == null) {
20 | return false;
21 | } else if (ransomNote == null) {
22 | return true;
23 | } else if (magazine == null) {
24 | return false;
25 | }
26 |
27 | int[] countR = new int[256];
28 | for (char c : ransomNote.toCharArray()) {
29 | countR[c]++;
30 | }
31 | int[] countM = new int[256];
32 | for (char c : magazine.toCharArray()) {
33 | countM[c]++;
34 | }
35 | for (int i = 0; i < 256; i++) {
36 | if (countR[i] > countM[i]) {
37 | return false;
38 | }
39 | }
40 | return true;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/RectangleArea.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Find the total area covered by two rectilinear rectangles in a 2D plane.
5 | *
13 | * [
14 | * [1, 3, 5, 7],
15 | * [10, 11, 16, 20],
16 | * [23, 30, 34, 50]
17 | * ]
18 | *
19 | *
20 | * Given target = 3, return true.
21 | */
22 | public class SearchA2DMatrix {
23 |
24 | public boolean searchMatrix(int[][] matrix, int target) {
25 | if (matrix == null) {
26 | return false;
27 | }
28 | return searchMatrixHelper(
29 | matrix,
30 | 0,
31 | matrix.length * matrix[0].length,
32 | target);
33 | }
34 |
35 | private boolean searchMatrixHelper(int[][] matrix, int start, int end,
36 | int target) {
37 | if (start >= end) {
38 | return false;
39 | }
40 | int mid = (start + end) / 2;
41 | int row = mid / matrix[0].length;
42 | int column = mid % matrix[0].length;
43 | if (matrix[row][column] == target) {
44 | return true;
45 | } else if (matrix[row][column] > target) {
46 | return searchMatrixHelper(matrix, start, mid, target);
47 | } else {
48 | return searchMatrixHelper(matrix, mid + 1, end, target);
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SearchA2DMatrix2.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the
5 | * following properties:
6 | *
14 | * [
15 | * [1, 4, 7, 11, 15],
16 | * [2, 5, 8, 12, 19],
17 | * [3, 6, 9, 16, 22],
18 | * [10, 13, 14, 17, 24],
19 | * [18, 21, 23, 26, 30]
20 | * ]
21 | *
22 | * Given target = 5, return true.
23 | *
14 | * [
15 | * [ 1, 2, 3 ],
16 | * [ 8, 9, 4 ],
17 | * [ 7, 6, 5 ]
18 | * ]
19 | */
20 | public class SpiralMatrixII {
21 |
22 | public int[][] generateMatrix(int n) {
23 | if (n == 0) {
24 | return new int[0][0];
25 | }
26 | int[][] board = new int[n][n];
27 | int num = 1;
28 |
29 | for (int layer = 0; layer <= (n - 1) / 2; layer++) {
30 | if (n - layer - 1 == layer) {
31 | board[layer][layer] = num;
32 | } else {
33 | // top
34 | for (int i = layer; i < n - layer - 1; i++) {
35 | board[layer][i] = num;
36 | num++;
37 | }
38 | // right
39 | for (int i = layer; i < n - layer - 1; i++) {
40 | board[i][n - layer - 1] = num;
41 | num++;
42 | }
43 | // btm
44 | for (int i = n - layer - 1; i > layer; i--) {
45 | board[n - layer - 1][i] = num;
46 | num++;
47 | }
48 | // right
49 | for (int i = n - layer - 1; i > layer; i--) {
50 | board[i][layer] = num;
51 | num++;
52 | }
53 | }
54 | }
55 | return board;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SumOfLeftLeaves.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.TreeNode;
4 |
5 | /**
6 | * Find the sum of all left leaves in a given binary tree.
7 | *
10 | * 3
11 | * / \
12 | * 9 20
13 | * / \
14 | * 15 7
15 | *
16 | * There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
17 | */
18 | public class SumOfLeftLeaves {
19 | public int sumOfLeftLeaves(TreeNode root) {
20 | if (root == null) {
21 | return 0;
22 | }
23 | return sumOfLeftLeavesHelperLeft(root.left) + sumOfLeftLeavesHelperRight(root.right);
24 | }
25 |
26 | private int sumOfLeftLeavesHelperLeft(TreeNode root) {
27 | if (root == null) {
28 | return 0;
29 | } else if (root.left == null && root.right == null) {
30 | return root.val;
31 | } else {
32 | return sumOfLeftLeavesHelperLeft(root.left) + sumOfLeftLeavesHelperRight(root.right);
33 | }
34 | }
35 |
36 | private int sumOfLeftLeavesHelperRight(TreeNode root) {
37 | if (root == null) {
38 | return 0;
39 | } else {
40 | return sumOfLeftLeavesHelperLeft(root.left) + sumOfLeftLeavesHelperRight(root.right);
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/SumRootToLeafNumbers.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.TreeNode;
4 |
5 | /**
6 | * Given a binary tree containing digits from 0-9 only, each root-to-leaf path
7 | * could represent a number.
8 | *
16 | * 1
17 | * / \
18 | * 2 3
19 | *
20 | *
21 | * The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path
22 | * 1->3 represents the number 13.
23 | *
12 | * 1
13 | * / \
14 | * 2 2
15 | * / \ / \
16 | * 3 4 4 3
17 | *
18 | *
19 | * But the following is not:
20 | *
21 | *
22 | * 1
23 | * / \
24 | * 2 2
25 | * \ \
26 | * 3 3
27 | *
28 | *
29 | * Note:
30 | *
10 | * For example, given array S = {-1 2 1 -4}, and target = 1.
11 | * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
12 | *
13 | */
14 | public class ThreeSumClosest {
15 | public int threeSumClosest(int[] nums, int target) {
16 | if (nums == null || nums.length == 0) {
17 | return Integer.MIN_VALUE;
18 | }
19 |
20 | nums = sort(nums);
21 |
22 | int min = Integer.MAX_VALUE;
23 | for (int i = 0; i < nums.length; i++) {
24 | int j = i + 1;
25 | int k = nums.length - 1;
26 | while (j < k) {
27 | int sum = nums[i] + nums[j] + nums[k];
28 | if (isSmaller(sum, target, min)) {
29 | min = target - sum;
30 | }
31 | if (min == 0) {
32 | return target;
33 | }
34 | if (sum <= target) {
35 | j++;
36 | } else {
37 | k--;
38 | }
39 | }
40 | }
41 | return target - min;
42 | }
43 |
44 | private boolean isSmaller(int sum, int target, int min) {
45 | return Math.abs(min) > Math.abs(target - sum);
46 | }
47 |
48 | private int[] sort(int[] nums) {
49 | Arrays.sort(nums);
50 | return nums;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/TopKFrequentElements.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 | import java.util.stream.Collectors;
8 |
9 | /**
10 | * Given a non-empty array of integers, return the k most frequent elements.
11 | *
17 | *
20 | */
21 | public class TopKFrequentElements {
22 | public List
12 | * 1 3 3 2 1
13 | * \ / / / \ \
14 | * 3 2 1 1 3 2
15 | * / / \ \
16 | * 2 1 2 3
17 | *
18 | */
19 | public class UniqueBinarySearchTrees {
20 |
21 | public int numTrees(int n) {
22 | if (n == 0 || n == 1) {
23 | return 1;
24 | }
25 | if (n < 0) {
26 | return -1;
27 | }
28 | int[] result = new int[n + 1];
29 | result[0] = 1;
30 | result[1] = 1;
31 |
32 | for (int i = 2; i <= n; i++) {
33 | for (int j = 0; j < i; j++) {
34 | result[i] += result[j] * result[i - j - 1];
35 | }
36 | }
37 | return result[n];
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/pengyifan/leetcode/UniquePaths.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | /**
4 | * A robot is located at the top-left corner of a m x n grid (marked 'Start' in
5 | * the diagram below).
6 | * > rst = c.findAll(new int[] { 1, 2, 3, 5 });
24 | assertEquals(2, rst.size());
25 | assertEquals(0, rst.get(0).get(0).intValue());
26 | assertEquals(2, rst.get(0).get(1).intValue());
27 |
28 | assertEquals(3, rst.get(1).get(0).intValue());
29 | assertEquals(3, rst.get(1).get(1).intValue());
30 | }
31 |
32 | @Test
33 | public void testFindAll3() {
34 | List
> rst = c.findAll(new int[] { 1, 2, 3, 5, 7 });
35 | assertEquals(3, rst.size());
36 | assertEquals(0, rst.get(0).get(0).intValue());
37 | assertEquals(2, rst.get(0).get(1).intValue());
38 |
39 | assertEquals(3, rst.get(1).get(0).intValue());
40 | assertEquals(3, rst.get(1).get(1).intValue());
41 |
42 | assertEquals(4, rst.get(2).get(0).intValue());
43 | assertEquals(4, rst.get(2).get(1).intValue());
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/CountAndSayTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | public class CountAndSayTest {
8 |
9 | private CountAndSay t = new CountAndSay();
10 |
11 | @Test
12 | public void testCountAndSay() throws Exception {
13 | assertEquals("11", t.countAndSay(2));
14 | assertEquals("111221", t.countAndSay(5));
15 | assertEquals("312211", t.countAndSay(6));
16 | }
17 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/DeleteNodeInALinkedListTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.ListNode;
4 | import org.junit.Test;
5 |
6 | import static org.junit.Assert.*;
7 |
8 | public class DeleteNodeInALinkedListTest {
9 |
10 | DeleteNodeInALinkedList t = new DeleteNodeInALinkedList();
11 |
12 | @Test
13 | public void testDeleteNode() throws Exception {
14 | ListNode a1 = new ListNode(0);
15 | ListNode a2 = new ListNode(1);
16 | ListNode a3 = new ListNode(0);
17 |
18 | a1.next = a2;
19 | a2.next = a3;
20 |
21 | t.deleteNode(a1);
22 | assertEquals(1, a1.val);
23 | assertEquals(0, a1.next.val);
24 | assertEquals(null, a1.next.next);
25 | }
26 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/DungeonGameTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | public class DungeonGameTest {
8 |
9 | DungeonGame s = new DungeonGame();
10 |
11 | @Test
12 | public void testCalculateMinimumHP() throws Exception {
13 | assertEquals(7, s.calculateMinimumHP(new int[][]{{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}}));
14 | }
15 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/EditDistanceTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 |
8 | public class EditDistanceTest {
9 |
10 | EditDistance s = new EditDistance();
11 |
12 | @Test
13 | public void testMinDistance() {
14 | assertEquals(1, s.minDistance("a", "ab"));
15 | assertEquals(1, s.minDistance("", "a"));
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/FactorialTrailingZeroesTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | public class FactorialTrailingZeroesTest {
8 |
9 | private FactorialTrailingZeroes t = new FactorialTrailingZeroes();
10 |
11 | @Test
12 | public void testTrailingZeroes() throws Exception {
13 | assertEquals(1, t.trailingZeroes(5));
14 | assertEquals(7, t.trailingZeroes(30));
15 | assertEquals(452137076, t.trailingZeroes(1808548329));
16 | }
17 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/FindTheDifferenceTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | public class FindTheDifferenceTest {
8 |
9 | private FindTheDifference t = new FindTheDifference();
10 |
11 | @Test
12 | public void testFindTheDifference() throws Exception {
13 | assertEquals('e', t.findTheDifference("abcd", "abcde"));
14 | assertEquals('y', t.findTheDifference("", "y"));
15 | }
16 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/FirstBadVersionTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | public class FirstBadVersionTest {
8 |
9 | @Test
10 | public void testFirstBadVersion() throws Exception {
11 | FirstBadVersion t = new FirstBadVersion(1702766719);
12 | assertEquals(t.firstBadVersion, t.firstBadVersion(2126753390));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/GasStationTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | public class GasStationTest {
8 |
9 | GasStation t = new GasStation();
10 |
11 | @Test
12 | public void test() {
13 | assertEquals(0, t.canCompleteCircuit(new int[] { 5 }, new int[] { 4 }));
14 | }
15 |
16 | @Test
17 | public void test2() {
18 | assertEquals(
19 | 1,
20 | t.canCompleteCircuit(new int[] { 1, 2 }, new int[] { 2, 1 }));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/GenerateParenthesesTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import java.util.List;
6 |
7 | import org.junit.Test;
8 |
9 |
10 | public class GenerateParenthesesTest {
11 |
12 | GenerateParentheses s = new GenerateParentheses();
13 |
14 | @Test
15 | public void testGenerateParenthesis() {
16 | List
8 | * 4
9 | * / \
10 | * 2 7
11 | * / \ / \
12 | * 1 3 6 9
13 | *
14 | * to
15 | *
16 | * 4
17 | * / \
18 | * 7 2
19 | * / \ / \
20 | * 9 6 3 1
21 | *
22 | */
23 | public class InvertBinaryTree {
24 | public TreeNode invertTree(TreeNode root) {
25 | invertTreeHelper(root);
26 | return root;
27 | }
28 |
29 | private void invertTreeHelper(TreeNode root) {
30 | if (root == null) {
31 | return;
32 | }
33 | invertTreeHelper(root.left);
34 | invertTreeHelper(root.right);
35 | TreeNode tmp = root.left;
36 | root.left = root.right;
37 | root.right = tmp;
38 | return;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/JumpGame2Test.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Before;
6 | import org.junit.Test;
7 |
8 | public class JumpGame2Test {
9 |
10 | private static int [] stairs;
11 |
12 | JumpGame2 t = new JumpGame2();
13 |
14 | @Test
15 | public void testJump() {
16 | assertEquals(2, t.jump(new int[] { 2, 3, 1, 1, 4 }));
17 | }
18 |
19 | @Before
20 | public void setUp() {
21 | stairs = new int[25002];
22 | for(int i=25000; i>= 0;i--) {
23 | stairs[25000-i] = i;
24 | }
25 | stairs[25000] = 1;
26 | stairs[25001] = 0;
27 | }
28 |
29 | @Test
30 | public void testJump2() {
31 | assertEquals(
32 | 2,
33 | t.jump(stairs));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/KthSmallestElementInABST.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import com.pengyifan.leetcode.commons.TreeNode;
4 |
5 | /**
6 | * Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
7 | * > lists = t.generate(5);
18 | assertThat(lists, hasItem(Arrays.asList(1)));
19 | assertThat(lists, hasItem(Arrays.asList(1, 1)));
20 | assertThat(lists, hasItem(Arrays.asList(1, 2, 1)));
21 | assertThat(lists, hasItem(Arrays.asList(1, 3, 3, 1)));
22 | assertThat(lists, hasItem(Arrays.asList(1, 4, 6, 4, 1)));
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/PermutationSequenceTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | public class PermutationSequenceTest {
8 |
9 | PermutationSequence t = new PermutationSequence();
10 |
11 | @Test
12 | public void testGetPermutation() {
13 | assertEquals("213", t.getPermutation(3, 3));
14 | }
15 |
16 | @Test
17 | public void testGetPermutation2() {
18 | assertEquals("1", t.getPermutation(1, 1));
19 | }
20 |
21 | @Test
22 | public void testGetPermutation3() {
23 | assertEquals("3412", t.getPermutation(4, 17));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/Permutations2Test.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.hamcrest.CoreMatchers.hasItem;
4 | import static org.junit.Assert.assertEquals;
5 | import static org.junit.Assert.assertThat;
6 |
7 | import java.util.Arrays;
8 | import java.util.List;
9 |
10 | import org.junit.Test;
11 |
12 | public class Permutations2Test {
13 |
14 | Permutations2 t = new Permutations2();
15 |
16 | @Test
17 | public void test() {
18 | List
> actual = t.permuteUnique(new int[] { 1, 1, 2 });
19 | assertEquals(3, actual.size());
20 | assertThat(actual, hasItem(Arrays.asList(1, 1, 2)));
21 | assertThat(actual, hasItem(Arrays.asList(1, 2, 1)));
22 | assertThat(actual, hasItem(Arrays.asList(2, 1, 1)));
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/PermutationsTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.hamcrest.CoreMatchers.hasItem;
4 | import static org.junit.Assert.assertThat;
5 |
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import org.junit.Test;
10 |
11 | public class PermutationsTest {
12 |
13 | Permutations t = new Permutations();
14 |
15 | @Test
16 | public void test() {
17 | List
> actual = t.permute(new int[] { 1, 2, 3 });
18 | assertThat(actual, hasItem(Arrays.asList(1, 2, 3)));
19 | assertThat(actual, hasItem(Arrays.asList(1, 3, 2)));
20 | assertThat(actual, hasItem(Arrays.asList(2, 1, 3)));
21 | assertThat(actual, hasItem(Arrays.asList(2, 3, 1)));
22 | assertThat(actual, hasItem(Arrays.asList(3, 1, 2)));
23 | assertThat(actual, hasItem(Arrays.asList(3, 2, 1)));
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/QueueReconstructionByHeightTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 | import static org.junit.Assert.*;
5 | import static org.junit.Assert.assertEquals;
6 |
7 | public class QueueReconstructionByHeightTest {
8 |
9 | private QueueReconstructionByHeight t = new QueueReconstructionByHeight();
10 |
11 | @Test
12 | public void testReconstructQueue() throws Exception {
13 | int[][] people = new int[][]{{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}};
14 | people = t.reconstructQueue(people);
15 | assertEquals(5, people[0][0]);
16 | assertEquals(7, people[5][0]);
17 | }
18 |
19 | @Test
20 | public void testReconstructQueue2() throws Exception {
21 | int[][] people = new int[][]{{8,2},{4,2},{4,5},{2,0},{7,2},{1,4},{9,1},{3,1},{9,0},{1,0}};
22 | people = t.reconstructQueue(people);
23 | assertEquals(1, people[0][0]);
24 | // assertEquals(7, people[5][0]);
25 | }
26 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/RectangleAreaTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | public class RectangleAreaTest {
8 |
9 | RectangleArea t = new RectangleArea();
10 |
11 | @Test
12 | public void testComputeArea() throws Exception {
13 | assertEquals(45, t.computeArea(-3, 0, 3, 4, 0, -1, 9, 2));
14 | assertEquals(16, t.computeArea(-2, -2, 2, 2, -2, -2, 2, 2));
15 | assertEquals(24, t.computeArea(-2, -2, 2, 2, -3, -3, 3, -1));
16 | }
17 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/RemoveDuplicatesFromSortedArrayTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | public class RemoveDuplicatesFromSortedArrayTest {
8 |
9 | RemoveDuplicatesFromSortedArray t = new RemoveDuplicatesFromSortedArray();
10 |
11 | @Test
12 | public void test() {
13 | int[] a = { 1, 1, 2 };
14 | assertEquals(2, t.removeDuplicates(a));
15 | assertEquals(1, a[0]);
16 | assertEquals(2, a[1]);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/RemoveDuplicatesFromSortedListIITest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | import com.pengyifan.leetcode.commons.ListNode;
8 |
9 |
10 | public class RemoveDuplicatesFromSortedListIITest {
11 |
12 | RemoveDuplicatesFromSortedListII s = new RemoveDuplicatesFromSortedListII();
13 |
14 | @Test
15 | public void testDeleteDuplicates() {
16 | int [] list = new int[] {1,2,3,3,4,4,5};
17 | ListNode head = creatList(list);
18 | head = s.deleteDuplicates(head);
19 | assertEquals(1, head.val);
20 | head = head.next;
21 | assertEquals(2, head.val);
22 | head = head.next;
23 | assertEquals(5, head.val);
24 | }
25 |
26 | @Test
27 | public void testDeleteDuplicates2() {
28 | int [] list = new int[] {1,1,1,2,3};
29 | ListNode head = creatList(list);
30 | head = s.deleteDuplicates(head);
31 | assertEquals(2, head.val);
32 | head = head.next;
33 | assertEquals(3, head.val);
34 | }
35 |
36 | private ListNode creatList(int[] list) {
37 | ListNode head = new ListNode(list[0]);
38 | ListNode p = head;
39 | for(int i=1; i
> actual = t.threeSum(new int[] { -1, 0, 1, 2, -1, -4 });
19 | assertEquals(2, actual.size());
20 | assertThat(actual, hasItem(Arrays.asList(-1, 0, 1)));
21 | assertThat(actual, hasItem(Arrays.asList(-1, -1, 2)));
22 | }
23 |
24 | @Test
25 | public void test_empty() {
26 | List
> actual = t.threeSum(new int[] {});
27 | assertEquals(0, actual.size());
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/TopKFrequentElementsTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.hamcrest.Matchers.containsInAnyOrder;
6 | import static org.junit.Assert.*;
7 |
8 | public class TopKFrequentElementsTest {
9 |
10 | private TopKFrequentElements t = new TopKFrequentElements();
11 | @Test
12 | public void testTopKFrequent() throws Exception {
13 | assertThat(t.topKFrequent(new int[]{1}, 1), containsInAnyOrder(1));
14 | assertThat(t.topKFrequent(new int[]{1,1,2,2,3}, 2), containsInAnyOrder(1,2));
15 | assertThat(t.topKFrequent(new int[]{4,1,-1,2,-1,2,3}, 2), containsInAnyOrder(-1,2));
16 | }
17 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/TwoSumIITest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | public class TwoSumIITest {
8 |
9 | private TwoSumII t = new TwoSumII();
10 |
11 | @Test
12 | public void testTwoSum() throws Exception {
13 | int[] r = t.twoSum(new int[]{2, 7, 11, 15}, 9);
14 | assertEquals(1, r[0]);
15 | assertEquals(2, r[1]);
16 | }
17 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/TwoSumTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 |
8 | public class TwoSumTest {
9 |
10 | TwoSum t = new TwoSum();
11 |
12 | @Test
13 | public void test() {
14 | int [] actual = t.twoSum(new int[]{2,7,11,15}, 9);
15 | assertEquals(1, actual[0]);
16 | assertEquals(2, actual[1]);
17 | }
18 |
19 | @Test
20 | public void test2() {
21 | int [] actual = t.twoSum(new int[]{5,75,25}, 100);
22 | assertEquals(2, actual[0]);
23 | assertEquals(3, actual[1]);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/UglyNumber2Test.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | public class UglyNumber2Test {
8 |
9 | UglyNumber2 t = new UglyNumber2();
10 |
11 | @Test
12 | public void testNthUglyNumber() throws Exception {
13 | assertEquals(12, t.nthUglyNumber(10));
14 | assertEquals(15, t.nthUglyNumber(11));
15 | }
16 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/UglyNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 | import static org.junit.Assert.assertFalse;
7 | import static org.junit.Assert.assertTrue;
8 |
9 | public class UglyNumberTest {
10 |
11 | UglyNumber t = new UglyNumber();
12 |
13 | @Test
14 | public void testIsUgly() throws Exception {
15 | assertTrue(t.isUgly(2));
16 | assertTrue(t.isUgly(6));
17 | assertFalse(t.isUgly(7));
18 | assertFalse(t.isUgly(0));
19 | }
20 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/UniquePathsTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 |
8 | public class UniquePathsTest {
9 |
10 | UniquePaths s = new UniquePaths();
11 |
12 | @Test
13 | public void test() {
14 | assertEquals(193536720, s.uniquePaths(23, 12));
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/ValidAnagramTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | public class ValidAnagramTest {
8 |
9 | ValidAnagram t = new ValidAnagram();
10 |
11 | @Test
12 | public void testIsAnagram() throws Exception {
13 | assertTrue(t.isAnagram("anagram", "nagaram"));
14 | assertFalse(t.isAnagram("rat", "car"));
15 | }
16 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/ValidNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 |
8 | public class ValidNumberTest {
9 |
10 | ValidNumber s = new ValidNumber();
11 |
12 | @Test
13 | public void testIsNumber() {
14 | assertTrue(s.isNumber("0"));
15 | assertTrue(s.isNumber(" 0.1 "));
16 | assertTrue(s.isNumber("2e10"));
17 | assertTrue(s.isNumber("1 "));
18 | assertTrue(s.isNumber(".1"));
19 | assertTrue(s.isNumber("01"));
20 | assertTrue(s.isNumber("2e0"));
21 | assertTrue(s.isNumber("+.8"));
22 | assertTrue(s.isNumber("46.e3"));
23 | assertTrue(s.isNumber(" 005047e+6"));
24 | assertTrue(s.isNumber("013455.e1 "));
25 |
26 | assertFalse(s.isNumber("abc"));
27 | assertFalse(s.isNumber("1 a"));
28 | assertFalse(s.isNumber("."));
29 | assertFalse(s.isNumber(". "));
30 | assertFalse(s.isNumber("-7e"));
31 | assertFalse(s.isNumber("92e1740e91"));
32 | assertFalse(s.isNumber("4e+"));
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/ValidPalindromeTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 |
8 | public class ValidPalindromeTest {
9 |
10 | ValidPalindrome s = new ValidPalindrome();
11 |
12 | @Test
13 | public void testIsPalindrome() {
14 | assertTrue(s.isPalindrome("A man, a plan, a canal: Panama"));
15 | assertTrue(s.isPalindrome(".,"));
16 | assertFalse(s.isPalindrome("1a2"));
17 | assertFalse(s.isPalindrome("race a car"));
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/ValidParenthesesTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | public class ValidParenthesesTest {
8 |
9 | ValidParentheses t = new ValidParentheses();
10 |
11 | @Test
12 | public void test() {
13 | assertTrue(t.isValid("()"));
14 | assertTrue(t.isValid("()[]{}"));
15 | assertFalse(t.isValid("(]"));
16 | assertFalse(t.isValid("([)]"));
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/ValidSudokuTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertTrue;
6 |
7 | public class ValidSudokuTest {
8 |
9 | private ValidSudoku t = new ValidSudoku();
10 |
11 | @Test
12 | public void testIsValidSudoku() throws Exception {
13 | String[] s = new String[]{".87654321", "2........", "3........", "4........", "5........",
14 | "6........", "7........", "8........", "9........"};
15 | char[][] board = getBoard(s);
16 | assertTrue(t.isValidSudoku(board));
17 | }
18 |
19 | private char[][] getBoard(String[] s) {
20 | char[][] board = new char[9][9];
21 | for (int i = 0; i < s.length; i++) {
22 | for (int j = 0; j < s[i].length(); j++) {
23 | board[i][j] = s[i].charAt(j);
24 | }
25 | }
26 | return board;
27 | }
28 | }
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/WildcardMatchingTest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | public class WildcardMatchingTest {
8 |
9 | WildcardMatching s = new WildcardMatching();
10 |
11 | @Test
12 | public void testIsMatch() {
13 | assertTrue(s.isMatch("aa", "aa"));
14 | assertTrue(s.isMatch("aa", "*"));
15 | assertTrue(s.isMatch("aa", "a*"));
16 | assertTrue(s.isMatch("ab", "?*"));
17 |
18 | assertFalse(s.isMatch("aa", "a"));
19 | assertFalse(s.isMatch("aaa", "aa"));
20 | assertFalse(s.isMatch("aab", "c*a*b"));
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/pengyifan/leetcode/WordBreakIITest.java:
--------------------------------------------------------------------------------
1 | package com.pengyifan.leetcode;
2 |
3 | import static org.junit.Assert.*;
4 | import static org.hamcrest.CoreMatchers.hasItem;
5 |
6 | import java.util.HashSet;
7 | import java.util.List;
8 | import java.util.Set;
9 |
10 | import org.junit.Test;
11 |
12 | public class WordBreakIITest {
13 |
14 | WordBreakII wordBreak = new WordBreakII();
15 |
16 | @Test
17 | public void testWordBreak() {
18 | String s = "catsanddog";
19 | String[] dictWords = new String[] { "cat", "cats", "and", "sand", "dog" };
20 | Set