├── .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 | 3 | pengyifan-leetcode 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016, Yifan Peng 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, this 11 | list of conditions and the following disclaimer in the documentation and/or 12 | other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 25 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pengyifan-leetcode 2 | 3 | My Java/Python solution for [Leetcode Online Judge](https://oj.leetcode.com/problems/). All the codes are tested using online-judge. Please feel free to let me know if you have any problem or better solutions. 4 | 5 | ### Requirements 6 | * Java version >= 1.6 7 | * Maven2 8 | * pytest 9 | 10 | ### Unit tests 11 | Almost all problems are accompanied by test cases. Some have corner test cases, others do not. 12 | ``` 13 | mvn test 14 | ``` 15 | 16 | ### Run pytest 17 | 18 | You can go to `src/main/python` then run 19 | 20 | ```bash 21 | pytest pyleetcode/xxx.py 22 | ``` 23 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.pengyifan.commons 6 | pengyifan-leetcode 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | pengyifan-leetcode 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | 20 | maven-compiler-plugin 21 | 3.1 22 | 23 | 1.8 24 | 1.8 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | junit 33 | junit 34 | 4.11 35 | test 36 | 37 | 38 | org.hamcrest 39 | hamcrest-all 40 | 1.3 41 | test 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/AddBinary.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given two binary strings, return their sum (also a binary string). 5 | *

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 inorderTraversal(TreeNode root) { 28 | ArrayList list = new ArrayList(); 29 | Stack s = new Stack(); 30 | if (root == null) { 31 | return list; 32 | } 33 | s.push(root); 34 | TreeNode prev = null; 35 | while (!s.isEmpty()) { 36 | TreeNode curr = s.pop(); 37 | if (prev == null || prev.left == curr || prev.right == curr) { 38 | if (curr.right != null) { 39 | s.push(curr.right); 40 | } 41 | s.push(curr); 42 | if (curr.left != null) { 43 | s.push(curr.left); 44 | } 45 | } else if (curr.left == null && curr.right == null) { 46 | list.add(curr.val); 47 | } else if (curr.right == prev) { 48 | ; 49 | } else { 50 | list.add(curr.val); 51 | } 52 | prev = curr; 53 | } 54 | return list; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/BulbSwitcher.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off 5 | * every second bulb. On the third round, you toggle every third bulb (turning on if it's off or 6 | * turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only 7 | * toggle the last bulb. Find how many bulbs are on after n rounds. 8 | *

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 | *

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 | *

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 set = new HashSet<>(); 17 | for (int i : nums) { 18 | if (set.contains(i)) { 19 | return true; 20 | } else { 21 | set.add(i); 22 | } 23 | } 24 | return false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/ContainsDuplicateII.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 and an integer k, find out whether there are two distinct indices i 8 | * and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. 9 | */ 10 | public class ContainsDuplicateII { 11 | public boolean containsNearbyDuplicate(int[] nums, int k) { 12 | Set set = new HashSet<>(); 13 | 14 | for (int j = 0; j < nums.length; j++) { 15 | if (j > k) { 16 | set.remove(nums[j - k - 1]); 17 | } 18 | if (!set.add(nums[j])) { 19 | return true; 20 | } 21 | } 22 | return false; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/ContainsDuplicateIII.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 an array of integers, find out whether there are two distinct indices i and j in the array 9 | * such that the difference between nums[i] and nums[j] is at most t and the difference between i 10 | * and j is at most k. 11 | */ 12 | public class ContainsDuplicateIII { 13 | public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { 14 | List list = new ArrayList<>(); 15 | for (int i = 0; i < nums.length; i++) { 16 | list.add(new C(i, nums[i])); 17 | } 18 | Collections.sort(list); 19 | 20 | for (int i = 0; i < list.size(); i++) { 21 | C c1 = list.get(i); 22 | for (int j = i + 1; j < list.size(); j++) { 23 | C c2 = list.get(j); 24 | if (Math.abs(c1.num - c2.num) <= t && Math.abs(c1.i - c2.i) <= k) { 25 | return true; 26 | } 27 | if (Math.abs(c1.num - c2.num) > t) { 28 | break; 29 | } 30 | } 31 | } 32 | return false; 33 | } 34 | 35 | class C implements Comparable { 36 | long num; 37 | int i; 38 | 39 | public C(int i, int num) { 40 | this.i = i; 41 | this.num = num; 42 | } 43 | 44 | @Override 45 | public int compareTo(C c) { 46 | int i = Long.compare(num, c.num); 47 | if (i == 0) { 48 | i = Integer.compare(i, c.i); 49 | } 50 | return i; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/ContiguousRanges.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class ContiguousRanges { 8 | 9 | public List> 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 solution = new ArrayList(); 19 | solution.add(target); 20 | solution.add(end); 21 | solutions.add(solution); 22 | target = end + 1; 23 | } 24 | return solutions; 25 | } 26 | 27 | private int binarySearch(int[] array, int target, int start, int end) { 28 | if (start == end) { 29 | return start; 30 | } else if (start + 1 == end) { 31 | if (array[end] - array[target] == end - target) { 32 | return end; 33 | } else { 34 | return start; 35 | } 36 | } 37 | int mid = (start + end) / 2; 38 | if (array[mid] - array[target] > mid - target) { 39 | return binarySearch(array, target, start, mid - 1); 40 | } else { 41 | return binarySearch(array, target, mid, end); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/CountAndSay.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * The count-and-say sequence is the sequence of integers beginning as follows: 5 | * 1, 11, 21, 1211, 111221, ... 6 | *

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 list = new ArrayList<>(); 27 | list.add(10); 28 | int f = 9; 29 | int x = 9; 30 | for (int i = 2; i <= n; i++) { 31 | f *= x; 32 | x--; 33 | list.add(f); 34 | } 35 | int sum = 0; 36 | for (int i : list) { 37 | sum += i; 38 | } 39 | return sum; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/CovertSortedArrayToBnarySearchTree.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import com.pengyifan.leetcode.commons.TreeNode; 4 | 5 | /** 6 | * Given an array where elements are sorted in ascending order, convert it to a 7 | * height balanced BST. 8 | */ 9 | public class CovertSortedArrayToBnarySearchTree { 10 | 11 | public TreeNode sortedArrayToBST(int[] num) { 12 | if (num == null || num.length == 0) { 13 | return null; 14 | } 15 | return sortedArraytoBSTHelper(num, 0, num.length); 16 | } 17 | 18 | private TreeNode sortedArraytoBSTHelper(int[] num, int start, int end) { 19 | if (start >= end) { 20 | return null; 21 | } 22 | int mid = (start + end)/2; 23 | TreeNode root = new TreeNode(num[mid]); 24 | root.left = sortedArraytoBSTHelper(num, start, mid); 25 | root.right = sortedArraytoBSTHelper(num, mid+1, end); 26 | return root; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/DeleteNodeInALinkedList.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import com.pengyifan.leetcode.commons.ListNode; 4 | 5 | /** 6 | * Write a function to delete a node (except the tail) in a singly linked list, given only access to 7 | * that node. 8 | *

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 | *

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 | *

6 | * Given a column title as appear in an Excel sheet, return its corresponding column number. 7 | *

8 | * For example: 9 | *

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 | *

6 | * For example: 7 | *

 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 |  * 

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 | *

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 | * 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 | *

 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 | *

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 generateParenthesis(int n) { 19 | if (n == 0) { 20 | return Collections.emptyList(); 21 | } 22 | List solutions = new ArrayList(); 23 | generateParenthesisHelper("", 0, 0, n, solutions); 24 | return solutions; 25 | } 26 | 27 | private void generateParenthesisHelper(String string, int left, int right, 28 | int n, 29 | List solutions) { 30 | if (left > n) { 31 | return; 32 | } 33 | if (left == n && right == n) { 34 | solutions.add(string); 35 | return; 36 | } 37 | generateParenthesisHelper(string + "(", left + 1, right, n, solutions); 38 | if (left > right) { 39 | generateParenthesisHelper(string + ")", left, right + 1, n, solutions); 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/HappyNumber.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Write an algorithm to determine if a number is "happy". 5 | *

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 | *

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 |  * 

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 set = new HashSet<>(nums1.length); 21 | for(int i: nums1) { 22 | set.add(i); 23 | } 24 | HashSet set2 = new HashSet<>(nums2.length); 25 | for(int i: nums2) { 26 | if (set.contains(i)) { 27 | set2.add(i); 28 | } 29 | } 30 | int [] r = new int[set2.size()]; 31 | int index = 0; 32 | for (int i: set2) { 33 | r[index] = i; 34 | index++; 35 | } 36 | return r; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/IsomorphicStrings.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Given two strings s and t, determine if they are isomorphic. 8 | *

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 map1 = new HashMap<>(); 31 | Map map2 = new HashMap<>(); 32 | for (int i = 0; i < s.length(); i++) { 33 | if (map1.containsKey(s.charAt(i))) { 34 | if (t.charAt(i) != map1.get(s.charAt(i))) { 35 | return false; 36 | } 37 | } else if (map2.containsKey(t.charAt(i))) { 38 | return false; 39 | } else { 40 | map1.put(s.charAt(i), t.charAt(i)); 41 | map2.put(t.charAt(i), s.charAt(i)); 42 | } 43 | } 44 | return true; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/LargestRectangleInHistogram.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given n non-negative integers representing the histogram's bar height where 5 | * the width of each bar is 1, find the area of largest rectangle in the 6 | * histogram. 7 | */ 8 | public class LargestRectangleInHistogram { 9 | 10 | public int largestRectangleArea(int[] height) { 11 | if (height == null || height.length == 0) { 12 | return 0; 13 | } 14 | int max = 0; 15 | int i = 0; 16 | int[] stack = new int[height.length]; 17 | int top = 0; 18 | while (i < height.length) { 19 | if (top == 0 || height[stack[top - 1]] <= height[i]) { 20 | stack[top] = i; 21 | top++; 22 | i++; 23 | } else { 24 | int left = stack[top - 1]; 25 | top--; 26 | int area = height[left] * (top == 0 ? i : i - stack[top - 1] - 1); 27 | if (max < area) { 28 | max = area; 29 | } 30 | } 31 | } 32 | while (top != 0) { 33 | int left = stack[top - 1]; 34 | top--; 35 | int area = height[left] * (top == 0 ? i : i - stack[top - 1] - 1); 36 | if (max < area) { 37 | max = area; 38 | } 39 | } 40 | return max; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/LengthOfLastWord.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given a string s consists of upper/lower-case alphabets and empty space 5 | * characters ' ', return the length of last word in the string. 6 | *

7 | * If the last word does not exist, return 0. 8 | *

9 | * Note: A word is defined as a character sequence consists of non-space 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 set = new HashSet(); 24 | for (int i = 0; i < num.length; i++) { 25 | set.add(num[i]); 26 | } 27 | 28 | for (int i = 0; i < num.length; i++) { 29 | int length = 1; 30 | int n = num[i]; 31 | // right 32 | while (set.contains(n + 1)) { 33 | length++; 34 | n++; 35 | set.remove(n); 36 | } 37 | n = num[i]; 38 | // left 39 | while (set.contains(n - 1)) { 40 | length++; 41 | n--; 42 | set.remove(n); 43 | } 44 | if (maxLength < length) { 45 | maxLength = length; 46 | } 47 | } 48 | return maxLength; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/LongestPalindrome.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given a string which consists of lowercase or uppercase letters, find the length of the longest 5 | * palindromes that can be built with those letters. 6 | *

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 | *

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 | * 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 map = new HashMap<>(); 28 | for (int i = 0; i < s.length(); i++) { 29 | char c = s.charAt(i); 30 | if (map.containsKey(c)) { 31 | max = Math.max(max, i - begin); 32 | int end = map.get(c) + 1; 33 | for (int j = begin; j < end; j++) { 34 | map.remove(s.charAt(j)); 35 | } 36 | begin = end; 37 | } 38 | map.put(c, i); 39 | } 40 | max = Math.max(max, s.length() - begin); 41 | return max; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/MajorityElement.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * Given an array of size n, find the majority element. The majority element is the element that 7 | * appears more than ⌊ n/2 ⌋ times. 8 | *

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 counter = new HashMap<>(); 14 | for (int i : nums) { 15 | if (counter.containsKey(i)) { 16 | counter.put(i, counter.get(i) + 1); 17 | } else { 18 | counter.put(i, 1); 19 | } 20 | } 21 | int max = 0; 22 | int mc = 0; 23 | for (int i: counter.keySet()) { 24 | if (mc < counter.get(i)) { 25 | max = i; 26 | mc = counter.get(i); 27 | } 28 | } 29 | return max; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/MaximumDepthOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import com.pengyifan.leetcode.commons.TreeNode; 4 | 5 | /** 6 | * Given a binary tree, find its maximum depth. 7 | *

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 | *

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 s; 29 | 30 | /** 31 | * initialize your data structure here. 32 | */ 33 | public MinStack() { 34 | s = new Stack<>(); 35 | } 36 | 37 | public void push(int x) { 38 | if (s.isEmpty()) { 39 | s.push(new Pair(x, x)); 40 | } else { 41 | s.push(new Pair(x, Math.min(x, s.peek().min))); 42 | } 43 | } 44 | 45 | public void pop() { 46 | s.pop(); 47 | } 48 | 49 | public int top() { 50 | return s.peek().val; 51 | } 52 | 53 | public int getMin() { 54 | return s.peek().min; 55 | } 56 | 57 | private class Pair { 58 | int val; 59 | int min; 60 | 61 | public Pair(int val, int min) { 62 | this.val = val; 63 | this.min = min; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/MinimumPathSum.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given a m x n grid filled with non-negative numbers, find a path from top 5 | * left to bottom right which minimizes the sum of all numbers along its path. 6 | */ 7 | public class MinimumPathSum { 8 | 9 | public int minPathSum(int[][] grid) { 10 | if (grid == null) { 11 | return 0; 12 | } 13 | int row = grid.length; 14 | int col = grid[row - 1].length; 15 | int[][] minVal = new int[row][col]; 16 | for (int i = 0; i < row; i++) { 17 | for (int j = 0; j < col; j++) { 18 | if (i == 0 && j == 0) { 19 | minVal[i][j] = grid[i][j]; 20 | } else if (i == 0) { 21 | minVal[i][j] = minVal[i][j - 1] + grid[i][j]; 22 | } else if (j == 0) { 23 | minVal[i][j] = minVal[i - 1][j] + grid[i][j]; 24 | } else { 25 | minVal[i][j] = Math.min(minVal[i - 1][j], minVal[i][j - 1]) 26 | + grid[i][j]; 27 | } 28 | } 29 | } 30 | return minVal[row - 1][col - 1]; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/MoveZeroes.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given an array nums, write a function to move all 0's to the end of it while maintaining the 5 | * relative order of the non-zero elements. 6 | *

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> generate(int numRows) { 13 | if (numRows <= 0) { 14 | return Collections.emptyList(); 15 | } 16 | List> lists = new ArrayList>(); 17 | List lastList = null; 18 | if (numRows >= 1) { 19 | List list = new ArrayList(); 20 | lists.add(list); 21 | lastList = list; 22 | list.add(1); 23 | } 24 | if (numRows >= 2) { 25 | List list = new ArrayList(); 26 | lists.add(list); 27 | lastList = list; 28 | list.add(1); 29 | list.add(1); 30 | } 31 | for (int i = 2; i < numRows; i++) { 32 | List list = new ArrayList(); 33 | lists.add(list); 34 | // first 35 | list.add(1); 36 | for (int j = 1; j < i; j++) { 37 | list.add(lastList.get(j - 1) + lastList.get(j)); 38 | } 39 | // last 40 | list.add(1); 41 | lastList = list; 42 | } 43 | return lists; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/PascalsTriangle2.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * Given an index k, return the kth row of the Pascal's triangle. 8 | *

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 getRow(int rowIndex) { 16 | if (rowIndex < 0) { 17 | throw new IllegalArgumentException(); 18 | } else if (rowIndex == 0) { 19 | return Arrays.asList(1); 20 | } else if (rowIndex == 1) { 21 | return Arrays.asList(1, 1); 22 | } else { 23 | Integer[] a = new Integer[rowIndex + 1]; 24 | a[0] = 1; 25 | a[1] = 1; 26 | for (int i = 2; i <= rowIndex; i++) { 27 | a[i] = 1; 28 | for (int j = i - 1; j > 0; j--) { 29 | a[j] = a[j] + a[j - 1]; 30 | } 31 | } 32 | return Arrays.asList(a); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/PathSum2.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import java.util.ArrayList; 4 | import com.pengyifan.leetcode.commons.TreeNode; 5 | 6 | /** 7 | * Given a binary tree and a sum, find all root-to-leaf paths where each path's 8 | * sum equals the given sum. For example: Given the below binary tree and sum = 9 | * 22, 10 | * 11 | *

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> pathSum(TreeNode root, int sum) { 28 | ArrayList> all = new ArrayList>(); 29 | if (root == null) { 30 | return all; 31 | } 32 | helper(root, sum, 0, new ArrayList(), all); 33 | return all; 34 | } 35 | 36 | public void helper(TreeNode root, int sum, int x, ArrayList path, 37 | ArrayList> all) { 38 | x += root.val; 39 | path.add(root.val); 40 | if (x == sum && root.left == null && root.right == null) { 41 | all.add(new ArrayList(path)); 42 | } else { 43 | if (root.left != null) { 44 | helper(root.left, sum, x, path, all); 45 | } 46 | if (root.right != null) { 47 | helper(root.right, sum, x, path, all); 48 | } 49 | } 50 | path.remove(path.size() - 1); 51 | return; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/PermutationSequence.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | /** 7 | * The set [1,2,3,…,n] contains a total of n! unique permutations. 8 | *

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 numbers = new LinkedList(); 28 | for (int i = 1; i <= n; i++) { 29 | numbers.add(i); 30 | } 31 | String output = ""; 32 | for (int i = n; i > 1; i--) { 33 | int devide = (int) (k / f); 34 | output += numbers.get(devide); 35 | numbers.remove(devide); 36 | k = (int) (k % f); 37 | f /= (i - 1); 38 | } 39 | output += numbers.get(0); 40 | return output; 41 | } 42 | 43 | private long factorial(int n) { 44 | long f = n; 45 | while (n != 1) { 46 | n--; 47 | f *= n; 48 | } 49 | return f; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/PlusOne.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given a non-negative number represented as an array of digits, plus one to 5 | * the number. 6 | *

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()); 15 | } else { 16 | return 1 / pow(x, -n, new HashMap()); 17 | } 18 | } 19 | 20 | private double pow(double x, int n, HashMap cache) { 21 | if (n == 0) { 22 | return 1; 23 | } 24 | if (n == 1) { 25 | return x; 26 | } 27 | if (cache.containsKey(n)) { 28 | return cache.get(n); 29 | } 30 | double p; 31 | if (n % 2 == 0) { 32 | p = pow(x, n / 2, cache) * pow(x, n / 2, cache); 33 | } else { 34 | p = pow(x, n / 2, cache) * pow(x, n / 2 + 1, cache); 35 | } 36 | cache.put(n, p); 37 | return p; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/PowerOfThree.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given an integer, write a function to determine if it is a power of three. 5 | */ 6 | public class PowerOfThree { 7 | public boolean isPowerOfThree(int n) { 8 | if (n <= 0) { 9 | return false; 10 | } 11 | while (n != 1) { 12 | if (n % 3 != 0) { 13 | return false; 14 | } 15 | n /= 3; 16 | } 17 | return true; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given an integer, write a function to determine if it is a power of two. 5 | */ 6 | public class PowerOfTwo { 7 | public boolean isPowerOfTwo(int n) { 8 | if (n <= 0) { 9 | return false; 10 | } 11 | while (n != 1) { 12 | if (n % 2 == 1) { 13 | return false; 14 | } 15 | n /= 2; 16 | } 17 | return true; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/ProductOfArrayExceptSelf.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given an array of n integers where n > 1, nums, return an array output such that output[i] is 5 | * equal to the product of all the elements of nums except nums[i]. 6 | *

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 | *

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 | *

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 | *

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 |  * 

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 6 | * Example1: x = 123, return 321 7 | *

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 stack = new Stack(); 20 | for (int i = 0; i < s.length(); i++) { 21 | char c = s.charAt(i); 22 | switch (state) { 23 | case 0: 24 | if (c == ' ') { 25 | start = -1; 26 | } else { 27 | start = i; 28 | state = 1; 29 | } 30 | break; 31 | case 1: 32 | if (c == ' ') { 33 | String word = s.substring(start, i); 34 | stack.push(word); 35 | start = -1; 36 | state = 0; 37 | } else { 38 | ; 39 | } 40 | } 41 | } 42 | // last word 43 | if (start != -1) { 44 | stack.push(s.substring(start)); 45 | } 46 | if (stack.isEmpty()) { 47 | return ""; 48 | } else { 49 | String output = stack.pop(); 50 | while (!stack.isEmpty()) { 51 | output += " " + stack.pop(); 52 | } 53 | return output; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/RotateArray.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Rotate an array of n elements to the right by k steps. 5 | *

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 | *

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 | *

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 | *

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 | *

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 | * Note: Your algorithm should have a linear runtime complexity. Could you 8 | * implement it without using extra memory? 9 | */ 10 | public class SingleNumber2 { 11 | 12 | public int singleNumber(int[] A) { 13 | int ones = 0, twos = 0; 14 | for (int i = 0; i < A.length; i++) { 15 | ones = (ones ^ A[i]) & ~twos; 16 | twos = (twos ^ A[i]) & ~ones; 17 | } 18 | return ones; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/SingleNumberIII.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given an array of numbers nums, in which exactly two elements appear only once and all the other 5 | * elements appear exactly twice. Find the two elements that appear only once. 6 | *

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 | *

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 |  * 

8 | * Example: 9 | *

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 | *

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 | *

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 | *

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 | *

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 | *

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 | *

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 | *

12 | * For example, 13 | * Given [1,1,1,2,2,3] and k = 2, return [1,2]. 14 | *

15 | * Note: 16 | *

    17 | *
  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • 18 | *
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
  • 19 | *
20 | */ 21 | public class TopKFrequentElements { 22 | public List topKFrequent(int[] nums, int k) { 23 | Map m = new HashMap<>(); 24 | for (int i : nums) { 25 | m.put(i, m.getOrDefault(i, 0) + 1); 26 | } 27 | List> l = m.entrySet().stream() 28 | .sorted((e1, e2) -> Integer.compare(e2.getValue(), e1.getValue())) 29 | .collect(Collectors.toList()); 30 | List rst = new ArrayList<>(); 31 | for (int i = 0; i < k && i < l.size(); i++) { 32 | rst.add(l.get(i).getKey()); 33 | } 34 | return rst; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/UglyNumber.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Write a program to check whether a given number is an ugly number. 5 | *

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 | *

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 | *

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 stack = new Stack(); 19 | stack.push(s.charAt(0)); 20 | for (int i = 1; i < s.length(); i++) { 21 | char c = s.charAt(i); 22 | switch (c) { 23 | case '(': 24 | case '{': 25 | case '[': 26 | stack.push(c); 27 | break; 28 | case ')': 29 | case '}': 30 | case ']': 31 | if (stack.isEmpty()) { 32 | return false; 33 | } 34 | char pop = stack.pop(); 35 | if (pop == '(' && c != ')') { 36 | return false; 37 | } 38 | if (pop == '{' && c != '}') { 39 | return false; 40 | } 41 | if (pop == '[' && c != ']') { 42 | return false; 43 | } 44 | break; 45 | default: 46 | return false; 47 | } 48 | } 49 | return stack.isEmpty(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/commons/ListNode.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode.commons; 2 | 3 | import java.util.HashSet; 4 | 5 | public class ListNode { 6 | 7 | public int val; 8 | public ListNode next; 9 | 10 | public ListNode(int x) { 11 | val = x; 12 | next = null; 13 | } 14 | 15 | public String toString() { 16 | HashSet set = new HashSet(); 17 | StringBuilder sb = new StringBuilder(); 18 | sb.append(val); 19 | ListNode p = this; 20 | set.add(p); 21 | while(p.next != null) { 22 | p = p.next; 23 | if (set.contains(p)) { 24 | break; 25 | } 26 | set.add(p); 27 | sb.append(" --> " + p.val); 28 | } 29 | return sb.toString(); 30 | } 31 | 32 | public static ListNode createList(int [] ints) { 33 | ListNode head = new ListNode(ints[0]); 34 | ListNode p = head; 35 | for(int i=1; i= 0; i--) { 21 | if (ints[i] != null) { 22 | nodes[i] = new TreeNode(ints[i]); 23 | } 24 | if (i * 2 + 1 < ints.length) { 25 | nodes[i].left = nodes[i * 2 + 1]; 26 | } 27 | if (i * 2 + 2 < ints.length) { 28 | nodes[i].right = nodes[i * 2 + 2]; 29 | } 30 | } 31 | return nodes[0]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/pengyifan/leetcode/commons/UndirectedGraphNode.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode.commons; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class UndirectedGraphNode { 6 | 7 | public int label; 8 | public ArrayList neighbors; 9 | 10 | public UndirectedGraphNode(int x) { 11 | label = x; 12 | neighbors = new ArrayList(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/python/pyleetcode/Array_Partition_I.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 4 | 5 | Example 1: 6 | Input: [1,4,3,2] 7 | 8 | Output: 4 9 | Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). 10 | 11 | Note: 12 | n is a positive integer, which is in the range of [1, 10000]. 13 | All the integers in the array will be in the range of [-10000, 10000]. 14 | """ 15 | 16 | class Solution(object): 17 | def arrayPairSum(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | return sum(sorted(nums)[::2]) -------------------------------------------------------------------------------- /src/main/python/pyleetcode/Merge_Two_Binary_Trees.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. 3 | 4 | You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. 5 | 6 | Example 1: 7 | Input: 8 | Tree 1 Tree 2 9 | 1 2 10 | / \ / \ 11 | 3 2 1 3 12 | / \ \ 13 | 5 4 7 14 | 15 | Output: 16 | Merged tree: 17 | 3 18 | / \ 19 | 4 5 20 | / \ \ 21 | 5 4 7 22 | Note: The merging process must start from the root nodes of both trees. 23 | """ 24 | 25 | from utils import TreeNode 26 | 27 | 28 | def mergeTrees(t1, t2): 29 | """ 30 | :type t1: TreeNode 31 | :type t2: TreeNode 32 | :rtype: TreeNode 33 | """ 34 | return mergeTrees_helper(t1, t2) 35 | 36 | 37 | def mergeTrees_helper(t1, t2): 38 | if t1 is None and t2 is None: 39 | return None 40 | elif t1 is None and t2 is not None: 41 | return t2 42 | elif t1 is not None and t2 is None: 43 | return t1 44 | else: 45 | t1.val += t2.val 46 | t1.left = mergeTrees_helper(t1.left, t2.left) 47 | t1.right = mergeTrees_helper(t1.right, t2.right) 48 | return t1 -------------------------------------------------------------------------------- /src/main/python/pyleetcode/Reverse_Words_in_a_String_III.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 3 | 4 | Example 1: 5 | 6 | Input: "Let's take LeetCode contest" 7 | Output: "s'teL ekat edoCteeL tsetnoc" 8 | 9 | Note: In the string, each word is separated by single space and there will not be any extra space in the string. 10 | """ 11 | 12 | def reverseWords(s): 13 | """ 14 | :type s: str 15 | :rtype: str 16 | """ 17 | if not s: 18 | return s 19 | return ' '.join([w[::-1] for w in s.split(' ')]) 20 | 21 | 22 | def test_reverseWords(): 23 | assert reverseWords("Let's take LeetCode contest") == "s'teL ekat edoCteeL tsetnoc" 24 | 25 | 26 | if __name__ == '__main__': 27 | test_reverseWords() 28 | -------------------------------------------------------------------------------- /src/main/python/pyleetcode/base_7.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer, return its base 7 string representation. 3 | 4 | Example 1: 5 | Input: 100 6 | 7 | Output: "202" 8 | Example 2: 9 | Input: -7 10 | 11 | Output: "-10" 12 | Note: The input will be in range of [-1e7, 1e7]. 13 | """ 14 | 15 | 16 | def convert_to_base7(num): 17 | """ 18 | :type num: int 19 | :rtype: str 20 | """ 21 | if num == 0: 22 | return '0' 23 | o = '' 24 | a = abs(num) 25 | while a != 0: 26 | o = str(a % 7) + o 27 | a /= 7 28 | return o if num > 0 else '-' + o 29 | 30 | 31 | def test_convert_to_base7(): 32 | assert convert_to_base7(100) == '202' 33 | assert convert_to_base7(-7) == '-10' 34 | assert convert_to_base7(0) == '0' 35 | 36 | 37 | if __name__ == '__main__': 38 | test_convert_to_base7() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/binary_watch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | d = { 3 | k: bin(k).count('1') for k in range(60) 4 | } 5 | 6 | def readBinaryWatch(self, num): 7 | """ 8 | :type num: int 9 | :rtype: List[str] 10 | """ 11 | return ['%d:%02d' % (h, m) for h in range(12) for m in range(60) if Solution.d[h] + Solution.d[m] == num] -------------------------------------------------------------------------------- /src/main/python/pyleetcode/construct_rectangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web 3 | page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 4 | 5 | 1. The area of the rectangular web page you designed must equal to the given target area. 6 | 7 | 2. The width W should not be larger than the length L, which means L >= W. 8 | 9 | 3. The difference between length L and width W should be as small as possible. 10 | You need to output the length L and the width W of the web page you designed in sequence. 11 | Example: 12 | Input: 4 13 | 14 | Output: [2, 2] 15 | 16 | Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. 17 | But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2. 18 | 19 | Note: 20 | 1. The given area won't exceed 10,000,000 and is a positive integer 21 | 2. The web page's width and length you designed must be positive integers. 22 | """ 23 | 24 | 25 | def construct_rectangle(area): 26 | """ 27 | :type area: int 28 | :rtype: List[int] 29 | """ 30 | import math 31 | w = math.floor(math.sqrt(area)) 32 | while w > 0: 33 | if area % w == 0: 34 | return [int(area/w), int(w)] 35 | w -= 1 36 | return [-1, -1] -------------------------------------------------------------------------------- /src/main/python/pyleetcode/defanging_an_ip_address.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a valid (IPv4) IP address, return a defanged version of that IP address. 3 | 4 | A defanged IP address replaces every period "." with "[.]". 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: address = "1.1.1.1" 11 | Output: "1[.]1[.]1[.]1" 12 | 13 | Example 2: 14 | 15 | Input: address = "255.100.50.0" 16 | Output: "255[.]100[.]50[.]0" 17 | 18 | 19 | Constraints: 20 | 21 | The given address is a valid IPv4 address. 22 | 23 | """ 24 | class Solution: 25 | def defangIPaddr(self, address: str) -> str: 26 | return '[.]'.join(address.split('.')) -------------------------------------------------------------------------------- /src/main/python/pyleetcode/find_disappeared_numbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers where 1 <= a[i] <= n (n = size of array), some elements appear twice and others appear once. 3 | 4 | Find all the elements of [1, n] inclusive that do not appear in this array. 5 | 6 | Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 7 | 8 | Example: 9 | 10 | Input: 11 | [4,3,2,7,8,2,3,1] 12 | 13 | Output: 14 | [5,6] 15 | """ 16 | 17 | 18 | def find_disappeared_numbers(nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: List[int] 22 | """ 23 | for i in range(len(nums)): 24 | index = abs(nums[i]) - 1 25 | nums[index] = - abs(nums[index]) 26 | 27 | return [i + 1 for i in range(len(nums)) if nums[i] > 0] 28 | 29 | 30 | def test_find_disappeared_numbers(): 31 | assert find_disappeared_numbers([4,3,2,7,8,2,3,1]) == [5,6] 32 | 33 | 34 | if __name__ == '__main__': 35 | test_find_disappeared_numbers() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/fizz_buzz.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that outputs the string representation of numbers from 1 to n. 3 | 4 | But for multiples of three it should output "Fizz" instead of the number and for the multiples of five output "Buzz". 5 | For numbers which are multiples of both three and five output "FizzBuzz". 6 | """ 7 | 8 | 9 | def fizz_buzz(n): 10 | """ 11 | :type n: int 12 | :rtype: List[str] 13 | """ 14 | output = [] 15 | for i in range(1, n+1): 16 | if i % 15 == 0: 17 | output.append('FizzBuzz') 18 | elif i % 3 == 0: 19 | output.append('Fizz') 20 | elif i % 5 == 0: 21 | output.append('Buzz') 22 | else: 23 | output.append(str(i)) 24 | return output 25 | 26 | 27 | def test_fizz_buzz(): 28 | expected = [ 29 | "1", 30 | "2", 31 | "Fizz", 32 | "4", 33 | "Buzz", 34 | "Fizz", 35 | "7", 36 | "8", 37 | "Fizz", 38 | "Buzz", 39 | "11", 40 | "Fizz", 41 | "13", 42 | "14", 43 | "FizzBuzz" 44 | ] 45 | assert fizz_buzz(15) == expected 46 | 47 | if __name__ == '__main__': 48 | test_fizz_buzz() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/hamming_distance.py: -------------------------------------------------------------------------------- 1 | """ 2 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 3 | 4 | Given two integers x and y, calculate the Hamming distance. 5 | 6 | Note: 7 | 0 <= x, y < 231. 8 | 9 | Example: 10 | 11 | Input: x = 1, y = 4 12 | 13 | Output: 2 14 | 15 | Explanation: 16 | 17 | 1 (0 0 0 1) 18 | 4 (0 1 0 0) 19 | ^ ^ 20 | 21 | The above arrows point to positions where the corresponding bits are different. 22 | """ 23 | 24 | 25 | def hamming_distance(x, y): 26 | """ 27 | :type x: int 28 | :type y: int 29 | :rtype: int 30 | """ 31 | n = 0 32 | while x != 0 and y != 0: 33 | if x % 2 != y % 2: 34 | n += 1 35 | x /= 2 36 | y /= 2 37 | m = x if x != 0 else y 38 | if m != 0: 39 | while m != 0: 40 | if m % 2 == 1: 41 | n += 1 42 | m /= 2 43 | return n 44 | 45 | 46 | def test_hammingDistance(): 47 | assert hamming_distance(1, 4) == 2 48 | 49 | if __name__ == '__main__': 50 | test_hammingDistance() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/jewels_and_stones.py: -------------------------------------------------------------------------------- 1 | """ 2 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 3 | 4 | The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 5 | 6 | Example 1: 7 | 8 | Input: J = "aA", S = "aAAbbbb" 9 | Output: 3 10 | 11 | Example 2: 12 | 13 | Input: J = "z", S = "ZZ" 14 | Output: 0 15 | 16 | Note: 17 | 18 | S and J will consist of letters and have length at most 50. 19 | The characters in J are distinct. 20 | """ 21 | class Solution: 22 | def numJewelsInStones(self, J: str, S: str) -> int: 23 | j = set(J) 24 | n = 0 25 | for c in S: 26 | if c in j: 27 | n += 1 28 | return n -------------------------------------------------------------------------------- /src/main/python/pyleetcode/judge_route_circle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. 3 | 4 | The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. 5 | 6 | Example 1: 7 | Input: "UD" 8 | Output: true 9 | 10 | Example 2: 11 | Input: "LL" 12 | Output: false 13 | """ 14 | import collections 15 | 16 | 17 | def judge_circle(moves): 18 | """ 19 | :type moves: str 20 | :rtype: bool 21 | """ 22 | c = collections.Counter(moves) 23 | return c['L'] == c['R'] and c['U'] == c['D'] 24 | 25 | 26 | def test_judge_circle(): 27 | assert judge_circle("UD") 28 | assert not judge_circle("LL") 29 | 30 | 31 | if __name__ == '__main__': 32 | test_judge_circle() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/keyboard_row.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American 3 | keyboard like the image below. 4 | 5 | Example 1: 6 | Input: ["Hello", "Alaska", "Dad", "Peace"] 7 | 8 | Output: ["Alaska", "Dad"] 9 | 10 | Note: 11 | - You may use one character in the keyboard more than once. 12 | - You may assume the input string will only contain letters of alphabet. 13 | 14 | """ 15 | 16 | 17 | def find_words(words): 18 | """ 19 | :type words: List[str] 20 | :rtype: List[str] 21 | """ 22 | keyboards = ['qwertyuiop', 23 | 'asdfghjkl', 24 | 'zxcvbnm',] 25 | out = [] 26 | for word in words: 27 | for row in keyboards: 28 | in_row = False 29 | not_in_row = False 30 | for c in word.lower(): 31 | if c in row: 32 | in_row = True 33 | else: 34 | not_in_row = True 35 | if in_row and not not_in_row: 36 | out.append(word) 37 | break 38 | return out 39 | 40 | 41 | def test_find_words(): 42 | input = ["Hello","Alaska","Dad","Peace"] 43 | expected = ["Alaska","Dad"] 44 | assert find_words(input) == expected 45 | 46 | input = ["asdfghjkl","qwertyuiop","zxcvbnm"] 47 | expected = ["asdfghjkl","qwertyuiop","zxcvbnm"] 48 | assert find_words(input) == expected 49 | 50 | 51 | if __name__ == '__main__': 52 | test_find_words() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/max_consecutive_ones.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary array, find the maximum number of consecutive 1s in this array. 3 | 4 | Example 1: 5 | Input: [1,1,0,1,1,1] 6 | 7 | Output: 3 8 | 9 | Explanation: The first two digits or the last three digits are consecutive 1s. 10 | The maximum number of consecutive 1s is 3. 11 | 12 | Note: 13 | - The input array will only contain 0 and 1. 14 | - The length of input array is a positive integer and will not exceed 10,000 15 | """ 16 | 17 | 18 | def find_max_consecutive_ones(nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: int 22 | """ 23 | total_m = 0 24 | sub_m = 0 25 | for i in nums: 26 | if i == 1: 27 | sub_m += 1 28 | else: 29 | total_m = max(total_m, sub_m) 30 | sub_m = 0 31 | return max(total_m, sub_m) 32 | 33 | 34 | def test_find_max_consecutive_ones(): 35 | assert find_max_consecutive_ones([1,1,0,1,1,1]) == 3 36 | 37 | if __name__ == '__main__': 38 | test_find_max_consecutive_ones() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/minimum_absolute_difference_in_BST.py: -------------------------------------------------------------------------------- 1 | """Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. 2 | 3 | Example: 4 | 5 | Input: 6 | 7 | 1 8 | \ 9 | 3 10 | / 11 | 2 12 | 13 | Output: 14 | 1 15 | 16 | Explanation: 17 | The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). 18 | Note: There are at least two nodes in this BST.""" 19 | 20 | 21 | def get_minimum_difference(root): 22 | """ 23 | :type root: TreeNode 24 | :rtype: int 25 | """ 26 | 27 | def _get_list(t, l): 28 | if t: 29 | l += [t.val] 30 | l = _get_list(t.left, l) 31 | l = _get_list(t.right, l) 32 | return l 33 | 34 | l = sorted(_get_list(root, [])) 35 | return min([abs(l[i] - l[i+1]) for i in range(0, len(l) - 1)]) 36 | 37 | -------------------------------------------------------------------------------- /src/main/python/pyleetcode/minimum_moves_to_equal_array_elements.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, 3 | where a move is incrementing n - 1 elements by 1. 4 | 5 | Example: 6 | 7 | Input: 8 | [1,2,3] 9 | 10 | Output: 11 | 3 12 | 13 | Explanation: 14 | Only three moves are needed (remember each move increments two elements): 15 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 16 | 17 | Hint: 18 | Add one to all the other elements is equivalent to subtract one from current element. 19 | """ 20 | 21 | 22 | def min_moves(nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: int 26 | """ 27 | m = min(nums) 28 | return sum(i - m for i in nums) 29 | 30 | 31 | def test_min_moves(): 32 | assert min_moves([1,2,3]) == 3 33 | assert min_moves([1,2147483647]) == 2147483646 34 | 35 | if __name__ == '__main__': 36 | test_min_moves() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/number_complement.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary 3 | representation. 4 | 5 | Note: 6 | - The given integer is guaranteed to fit within the range of a 32-bit signed integer. 7 | - You could assume no leading zero bit in the integer's binary representation. 8 | 9 | Example 1: 10 | Input: 5 11 | 12 | Output: 2 13 | 14 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need 15 | to output 2. 16 | 17 | Example 2: 18 | Input: 1 19 | 20 | Output: 0 21 | 22 | Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to 23 | output 0. 24 | """ 25 | 26 | 27 | def find_complement(num): 28 | """ 29 | :type num: int 30 | :rtype: int 31 | """ 32 | def _get_digit(x): 33 | n = 0 34 | while x != 0: 35 | n += 1 36 | x /= 2 37 | return n 38 | 39 | # total = 2 ** 32 - 1 40 | # return total - num - (total - 2 ** n + 1) 41 | return 2 ** _get_digit(num) - num - 1 42 | 43 | 44 | def test_find_complement(): 45 | assert find_complement(5) == 2 46 | assert find_complement(1) == 0 47 | 48 | if __name__ == '__main__': 49 | test_find_complement() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/reverse_string_ii.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the 3 | start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but 4 | greater than or equal to k characters, then reverse the first k characters and left the other as original. 5 | 6 | Example: 7 | Input: s = "abcdefg", k = 2 8 | 9 | Output: "bacdfeg" 10 | Restrictions: 11 | * The string consists of lower English letters only. 12 | * Length of the given string and k will in the range [1, 10000] 13 | """ 14 | 15 | 16 | def reverse_str(s, k): 17 | """ 18 | :type s: str 19 | :type k: int 20 | :rtype: str 21 | """ 22 | if k == 0: 23 | return s 24 | 25 | o = '' 26 | for idx in range(0, len(s), k): 27 | if idx/k % 2 == 0: 28 | o += s[idx:idx+k][::-1] 29 | else: 30 | o += s[idx:idx+k] 31 | idx += k 32 | return o 33 | 34 | 35 | def test_reverse_str(): 36 | assert reverse_str('abcdefg', 2) == "bacdfeg" 37 | 38 | if __name__ == '__main__': 39 | test_reverse_str() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/split_a_string_in_balanced_strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def balancedStringSplit(self, s: str) -> int: 3 | n = 0 4 | r = 0 5 | for c in s: 6 | if c == 'R': 7 | r += 1 8 | else: 9 | r -= 1 10 | if r == 0: 11 | n += 1 12 | return n 13 | 14 | def test_balancedStringSplit(self): 15 | assert self.balancedStringSplit('RLRRLLRLRL') == 4 16 | 17 | 18 | if __name__ == "__main__": 19 | s = Solution() 20 | s.test_balancedStringSplit() -------------------------------------------------------------------------------- /src/main/python/pyleetcode/utils.py: -------------------------------------------------------------------------------- 1 | class TreeNode(object): 2 | def __init__(self, x): 3 | self.val = x 4 | self.left = None 5 | self.right = None -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/ArrayBalancePointTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class ArrayBalancePointTest { 9 | 10 | ArrayBalancePoint s = new ArrayBalancePoint(); 11 | 12 | @Test 13 | public void testBalancePoint() { 14 | assertEquals(3, s.balancePoint(new int[] {5, 4, 0, 19, 3, 4, 2, 0})); 15 | assertEquals(-1, s.balancePoint(new int[] {5, 4, 2, 1})); 16 | assertEquals(2, s.balancePoint(new int[] {5, 4, 0, 3, 4, 2, 0})); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/BestTimeToBuyAndSellStockTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class BestTimeToBuyAndSellStockTest { 8 | 9 | BestTimeToBuyAndSellStock s = new BestTimeToBuyAndSellStock(); 10 | 11 | @Test 12 | public void testMaxProfit() { 13 | assertEquals(0, s.maxProfit(new int[] { 2, 1 })); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/BinaryTreePathsTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import com.pengyifan.leetcode.commons.TreeNode; 4 | import java.util.List; 5 | import org.junit.Test; 6 | 7 | import static org.hamcrest.Matchers.containsInAnyOrder; 8 | import static org.junit.Assert.assertThat; 9 | 10 | public class BinaryTreePathsTest { 11 | 12 | private BinaryTreePaths t = new BinaryTreePaths(); 13 | 14 | @Test 15 | public void testBinaryTreePaths() throws Exception { 16 | Integer[] ints = new Integer[]{1, 2, 3, null, 5}; 17 | TreeNode r = TreeNode.createList(ints); 18 | List rst = t.binaryTreePaths(r); 19 | assertThat(rst, containsInAnyOrder("1->2->5", "1->3")); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/BullsAndCowsTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class BullsAndCowsTest { 8 | 9 | private BullsAndCows t = new BullsAndCows(); 10 | 11 | @Test 12 | public void testGetHint() throws Exception { 13 | assertEquals("1A3B", t.getHint("1807", "7810")); 14 | assertEquals("1A1B", t.getHint("1123", "0111")); 15 | assertEquals("0A4B", t.getHint("1122", "2211")); 16 | assertEquals("3A0B", t.getHint("1122", "1222")); 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/CandyTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class CandyTest { 9 | 10 | Candy candy = new Candy(); 11 | 12 | @Test 13 | public void testCandy() { 14 | assertEquals(6, candy.candy(new int[]{5,3,1})); 15 | } 16 | 17 | @Test 18 | public void testCandy2() { 19 | int[] ratings = new int[20000]; 20 | int sum = 0; 21 | for(int i=0;i> rst = c.findAll(new int[] { 1, 2, 3, 4, 5 }); 16 | assertEquals(1, rst.size()); 17 | assertEquals(0, rst.get(0).get(0).intValue()); 18 | assertEquals(4, rst.get(0).get(1).intValue()); 19 | } 20 | 21 | @Test 22 | public void testFindAll2() { 23 | List> 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 solutions = s.generateParenthesis(3); 17 | assertEquals(5, solutions.size()); 18 | assertTrue(solutions.contains("()()()")); 19 | assertTrue(solutions.contains("()(())")); 20 | assertTrue(solutions.contains("(())()")); 21 | assertTrue(solutions.contains("((()))")); 22 | assertTrue(solutions.contains("(()())")); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/HappyNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class HappyNumberTest { 8 | 9 | private HappyNumber t = new HappyNumber(); 10 | 11 | @Test 12 | public void testIsHappy() throws Exception { 13 | assertTrue(t.isHappy(19)); 14 | assertFalse(t.isHappy(2)); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/HouseRobberIIITest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import com.pengyifan.leetcode.commons.TreeNode; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.assertEquals; 7 | 8 | public class HouseRobberIIITest { 9 | 10 | private HouseRobberIII t = new HouseRobberIII(); 11 | 12 | @Test 13 | public void testRob() throws Exception { 14 | assertEquals(7, t.rob(TreeNode.createList(new Integer[]{3, 2, 3, null, 3, null, 1}))); 15 | assertEquals(9, t.rob(TreeNode.createList(new Integer[]{3, 4, 5, 1, 3, null, 1}))); 16 | 17 | System.out.println(t.rob(TreeNode.createList(new Integer[]{3, 4, 5, 1, 3, null, 1}))); 18 | } 19 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/HouseRobberTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | public class HouseRobberTest { 6 | 7 | private HouseRobber t = new HouseRobber(); 8 | 9 | @Test 10 | public void testRob() throws Exception { 11 | int[] is = new int[]{226, 174, 214, 16, 218, 48, 153, 131, 128, 17, 157, 142, 88, 43, 37, 157, 12 | 43, 221, 191, 68, 206, 23, 225, 82, 54, 118, 111, 46, 80, 49, 245, 63, 25, 194, 72, 80, 143, 13 | 55, 209, 18, 55, 122, 65, 66, 177, 101, 63, 201, 172, 130, 103, 225, 142, 46, 86, 185, 62, 14 | 138, 212, 192, 125, 77, 223, 188, 99, 228, 90, 25, 193, 211, 84, 239, 119, 234, 85, 83, 123, 15 | 120, 131, 203, 219, 10, 82, 35, 120, 180, 249, 106, 37, 169, 225, 54, 103, 55, 166, 124}; 16 | System.out.println(t.rob(is)); 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/IntegerBreakTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class IntegerBreakTest { 8 | 9 | private IntegerBreak t = new IntegerBreak(); 10 | 11 | @Test 12 | public void testIntegerBreak() throws Exception { 13 | assertEquals(1, t.integerBreak(2)); 14 | assertEquals(36, t.integerBreak(10)); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/IntegerToEnglishWordsTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertEquals; 6 | 7 | public class IntegerToEnglishWordsTest { 8 | 9 | IntegerToEnglishWords t = new IntegerToEnglishWords(); 10 | 11 | @Test 12 | public void testNumberToWords() throws Exception { 13 | assertEquals("One Hundred", t.numberToWords(100)); 14 | assertEquals("One Hundred Twenty Three", t.numberToWords(123)); 15 | assertEquals("Twelve Thousand Three Hundred Forty Five", t.numberToWords(12345)); 16 | assertEquals("One Hundred Thousand", t.numberToWords(100000)); 17 | assertEquals("One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven", t.numberToWords(1234567)); 18 | assertEquals("One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One", t.numberToWords(1234567891)); 19 | } 20 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/InterleavingStringTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class InterleavingStringTest { 9 | 10 | InterleavingString t = new InterleavingString(); 11 | 12 | @Test 13 | public void testIsInterleave() { 14 | assertTrue(t.isInterleave("aabcc", "dbbca", "aadbbcbcac")); 15 | assertFalse(t.isInterleave("aabcc", "dbbca", "aadbbbaccc")); 16 | } 17 | 18 | @Test 19 | public void testIsInterleave2() { 20 | assertTrue(t.isInterleave("a", "", "a")); 21 | } 22 | 23 | @Test 24 | public void testIsInterleave_null() { 25 | assertFalse(t.isInterleave(null, "dbbca", "aadbbbaccc")); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/InvertBinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import com.pengyifan.leetcode.commons.TreeNode; 4 | 5 | /** 6 | * Invert a binary tree. 7 | *

 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 | *

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 | // 20 | private int[] kthSmallestHelper(TreeNode root, int k) { 21 | if (root == null) { 22 | return new int[]{0, 0}; 23 | } 24 | int[] left = kthSmallestHelper(root.left, k); 25 | if (left[0] == -1) { 26 | return left; 27 | } 28 | if (left[0] == k - 1) { 29 | left[0] = -1; 30 | left[1] = root.val; 31 | return left; 32 | } 33 | int[] right = kthSmallestHelper(root.right, k - left[0] - 1); 34 | if (right[0] == -1) { 35 | return right; 36 | } 37 | right[0] = left[0] + right[0] + 1; 38 | return right; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/LargestRectangleInHistogramTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class LargestRectangleInHistogramTest { 9 | 10 | LargestRectangleInHistogram t = new LargestRectangleInHistogram(); 11 | 12 | @Test 13 | public void test() { 14 | assertEquals(10, t.largestRectangleArea(new int[] {2,1,5,6,2,3})); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/LengthOfLastWordTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class LengthOfLastWordTest { 9 | 10 | LengthOfLastWord t = new LengthOfLastWord(); 11 | 12 | @Test 13 | public void testLengthOfLastWord() { 14 | assertEquals(5, t.lengthOfLastWord("Hello World")); 15 | } 16 | 17 | @Test 18 | public void testLengthOfLastWord2() { 19 | assertEquals(1, t.lengthOfLastWord("a ")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/LinkedListCycle2Test.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 LinkedListCycle2Test { 10 | 11 | LinkedListCycle2 t = new LinkedListCycle2(); 12 | 13 | @Test 14 | public void test() { 15 | ListNode n1 = new ListNode(1); 16 | ListNode n2 = new ListNode(2); 17 | n1.next = n2; 18 | assertNull(t.detectCycle(n1)); 19 | } 20 | 21 | @Test 22 | public void test2() { 23 | ListNode n1 = new ListNode(3); 24 | ListNode n2 = new ListNode(2); 25 | ListNode n3 = new ListNode(0); 26 | ListNode n4 = new ListNode(-4); 27 | n1.next = n2; 28 | n2.next = n3; 29 | n3.next = n4; 30 | n4.next = n1; 31 | assertEquals(n1, t.detectCycle(n1)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/LongestConsecutiveSequenceTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class LongestConsecutiveSequenceTest { 8 | 9 | LongestConsecutiveSequence s = new LongestConsecutiveSequence(); 10 | 11 | @Test 12 | public void testLongestConsecutive() { 13 | assertEquals(4, s.longestConsecutive(new int[] { 100, 4, 200, 1, 3, 2 })); 14 | assertEquals(3, s.longestConsecutive(new int[] { 1, 2, 0, 1 })); 15 | } 16 | 17 | @Test 18 | public void testLongestConsecutive2() { 19 | assertEquals( 20 | 9, 21 | s.longestConsecutive(new int[] { 0, 3, 7, 2, 5, 8, 4, 6, 0, 1 })); 22 | } 23 | 24 | @Test 25 | public void testLongestConsecutive_null() { 26 | assertEquals(0, s.longestConsecutive(null)); 27 | } 28 | 29 | @Test 30 | public void testLongestConsecutive_empty() { 31 | assertEquals(0, s.longestConsecutive(new int[] {})); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/LongestSubstringWithoutRepeatingCharactersTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class LongestSubstringWithoutRepeatingCharactersTest { 8 | 9 | private LongestSubstringWithoutRepeatingCharacters t = 10 | new LongestSubstringWithoutRepeatingCharacters(); 11 | 12 | @Test 13 | public void testLengthOfLongestSubstring() throws Exception { 14 | assertEquals(1, t.lengthOfLongestSubstring("eee")); 15 | assertEquals(3, t.lengthOfLongestSubstring("dvdf")); 16 | assertEquals(3, t.lengthOfLongestSubstring("abcabcbb")); 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/MaximumProductSubarrayTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class MaximumProductSubarrayTest { 8 | 9 | MaximumProductSubarray s = new MaximumProductSubarray(); 10 | 11 | @Test 12 | public void testMaxProduct() { 13 | assertEquals(-2, s.maxProduct(new int[] { -2 })); 14 | assertEquals(6, s.maxProduct(new int[] { 2, 3 })); 15 | assertEquals(0, s.maxProduct(new int[] { -2, 0, -1 })); 16 | assertEquals(180, s.maxProduct(new int[] { 6, -3, -10, 0, 2 })); 17 | assertEquals(60, s.maxProduct(new int[] { -1, -3, -10, 0, 60 })); 18 | assertEquals(80, s.maxProduct(new int[] { -2, -3, 0, -2, -40 })); 19 | assertEquals(1, s.maxProduct(new int[] { -1, -1 })); 20 | } 21 | 22 | @Test 23 | public void testMaxProduct2() { 24 | assertEquals(4, s.maxProduct(new int[] { 2, -1, -1, 2, 0, -3, 3 })); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/MedianFinderTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class MedianFinderTest { 8 | 9 | @Test 10 | public void testFindMedian() throws Exception { 11 | MedianFinder mf = new MedianFinder(); 12 | mf.addNum(6); 13 | assertEquals(6, mf.findMedian(), 0.000001); 14 | mf.addNum(10); 15 | assertEquals(8, mf.findMedian(), 0.000001); 16 | mf.addNum(2); 17 | assertEquals(6, mf.findMedian(), 0.000001); 18 | mf.addNum(6); 19 | assertEquals(6, mf.findMedian(), 0.000001); 20 | mf.addNum(5); 21 | assertEquals(6, mf.findMedian(), 0.000001); 22 | mf.addNum(0); 23 | assertEquals(5.5, mf.findMedian(), 0.000001); 24 | mf.addNum(6); 25 | assertEquals(6, mf.findMedian(), 0.000001); 26 | mf.addNum(3); 27 | assertEquals(5.5, mf.findMedian(), 0.000001); 28 | mf.addNum(1); 29 | assertEquals(5, mf.findMedian(), 0.000001); 30 | mf.addNum(0); 31 | assertEquals(4, mf.findMedian(), 0.000001); 32 | mf.addNum(0); 33 | assertEquals(3, mf.findMedian(), 0.000001); 34 | } 35 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/MergeSortedArrayTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class MergeSortedArrayTest { 9 | 10 | MergeSortedArray s = new MergeSortedArray(); 11 | 12 | @Test 13 | public void testMerge() { 14 | int [] A = new int[1]; 15 | int [] B = new int[]{1}; 16 | s.merge(A, 0, B, 1); 17 | assertEquals(1, A[0]); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/MinimumPathSumTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import org.junit.Test; 6 | 7 | public class MinimumPathSumTest { 8 | 9 | MinimumPathSum t = new MinimumPathSum(); 10 | 11 | @Test 12 | public void test() { 13 | assertEquals(2, t.minPathSum(new int[][] {{0,1},{2,1}})); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/MinimumWindowSubstringTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class MinimumWindowSubstringTest { 9 | 10 | MinimumWindowSubstring s = new MinimumWindowSubstring(); 11 | 12 | @Test 13 | public void testMinWindow() { 14 | assertEquals("BANC", s.minWindow("ADOBECODEBANC", "ABC")); 15 | } 16 | 17 | @Test 18 | public void testMinWindow2() { 19 | assertEquals("aa", s.minWindow("aa", "aa")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/MissingNumber.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | /** 4 | * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is 5 | * missing from the array. 6 | *

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> 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 8 | * Example 9 | *

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 ips = t.restoreIpAddresses("25525511135"); 18 | assertEquals(2, ips.size()); 19 | assertThat(ips, hasItem("255.255.11.135")); 20 | assertThat(ips, hasItem("255.255.111.35")); 21 | } 22 | 23 | @Test 24 | public void test2() { 25 | List ips = t.restoreIpAddresses("0000"); 26 | assertEquals(1, ips.size()); 27 | assertThat(ips, hasItem("0.0.0.0")); 28 | } 29 | 30 | @Test 31 | public void test3() { 32 | List ips = t.restoreIpAddresses("010010"); 33 | assertEquals(2, ips.size()); 34 | assertThat(ips, hasItem("0.10.0.10")); 35 | assertThat(ips, hasItem("0.100.1.0")); 36 | } 37 | 38 | 39 | @Test 40 | public void test_null() { 41 | assertEquals(0, t.restoreIpAddresses(null).size()); 42 | assertEquals(0, t.restoreIpAddresses("").size()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/ReverseLinkedListTest.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 ReverseLinkedListTest { 9 | 10 | private ReverseLinkedList t = new ReverseLinkedList(); 11 | 12 | @Test 13 | public void testReverseList() throws Exception { 14 | ListNode l = ListNode.createList(new int[]{1,2}); 15 | l = t.reverseList(l); 16 | assertEquals(2, l.val); 17 | assertEquals(1, l.next.val); 18 | } 19 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/ReverseVowelsOfAStringTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class ReverseVowelsOfAStringTest { 8 | 9 | private ReverseVowelsOfAString t = new ReverseVowelsOfAString(); 10 | 11 | @Test 12 | public void testReverseVowels() throws Exception { 13 | assertEquals("holle", t.reverseVowels("hello")); 14 | assertEquals("leotcede", t.reverseVowels("leetcode")); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/ReverseWordsInAStringTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import org.junit.Test; 6 | 7 | public class ReverseWordsInAStringTest { 8 | 9 | private ReverseWordsInAString t = new ReverseWordsInAString(); 10 | 11 | @Test 12 | public void testReverseWords() { 13 | assertEquals("blue is sky the", t.reverseWords("the sky is blue")); 14 | } 15 | 16 | @Test 17 | public void testReverseWords_empty() { 18 | assertEquals("", t.reverseWords("")); 19 | } 20 | 21 | @Test 22 | public void testReverseWords_null() { 23 | assertEquals(null, t.reverseWords(null)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/RomanToIntegerTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class RomanToIntegerTest { 9 | 10 | RomanToInteger s = new RomanToInteger(); 11 | 12 | @Test 13 | public void testRomanToInt() { 14 | assertEquals(2014, s.romanToInt("MMXIV")); 15 | assertEquals(1903, s.romanToInt("MDCDIII")); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/RotateArrayTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class RotateArrayTest { 8 | 9 | RotateArray s = new RotateArray(); 10 | 11 | @Test 12 | public void testRotate() throws Exception { 13 | int [] i = new int[]{-1,-100,3,99}; 14 | s.rotate(i, 3); 15 | assertEquals(-100, i[0]); 16 | assertEquals(-1, i[i.length - 1]); 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/RotateImageTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class RotateImageTest { 8 | 9 | RotateImage t = new RotateImage(); 10 | 11 | @Test 12 | public void test() { 13 | int[][] matrix = new int[][] { { 1, 2 }, { 3, 4 } }; 14 | int[][] expected = new int[][] { { 3, 1 }, { 4, 2 } }; 15 | t.rotate(matrix); 16 | assertArrayEquals(expected[0], matrix[0]); 17 | assertArrayEquals(expected[1], matrix[1]); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/RotateListTest.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 RotateListTest { 11 | 12 | RotateList t = new RotateList(); 13 | 14 | @Test 15 | public void testRotateRight() { 16 | ListNode a = new ListNode(1); 17 | ListNode b = new ListNode(2); 18 | ListNode c = new ListNode(3); 19 | ListNode d = new ListNode(4); 20 | ListNode e = new ListNode(5); 21 | a.next = b; 22 | b.next = c; 23 | c.next = d; 24 | d.next = e; 25 | ListNode actual = t.rotateRight(a, 2); 26 | assertEquals(4, actual.val); 27 | actual = actual.next; 28 | assertEquals(5, actual.val); 29 | actual = actual.next; 30 | assertEquals(1, actual.val); 31 | actual = actual.next; 32 | assertEquals(2, actual.val); 33 | actual = actual.next; 34 | assertEquals(3, actual.val); 35 | actual = actual.next; 36 | assertEquals(null, actual); 37 | } 38 | 39 | @Test 40 | public void testRotateRight2() { 41 | ListNode a = new ListNode(1); 42 | ListNode actual = t.rotateRight(a, 1); 43 | assertEquals(1, actual.val); 44 | } 45 | 46 | @Test 47 | public void testRotateRight3() { 48 | ListNode a = new ListNode(1); 49 | ListNode actual = t.rotateRight(a, 99); 50 | assertEquals(1, actual.val); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/SearchForARangeTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class SearchForARangeTest { 8 | 9 | SearchForARange t = new SearchForARange(); 10 | 11 | @Test 12 | public void testSearchRange() { 13 | int[] actual = t.searchRange(new int[] { 5, 7, 7, 8, 8, 10 }, 8); 14 | assertEquals(3, actual[0]); 15 | assertEquals(4, actual[1]); 16 | } 17 | 18 | @Test 19 | public void testSearchRange2() { 20 | int[] actual = t.searchRange(new int[] { 1 }, 0); 21 | assertEquals(-1, actual[0]); 22 | assertEquals(-1, actual[1]); 23 | } 24 | 25 | @Test 26 | public void testSearchRange3() { 27 | int[] actual = t.searchRange(new int[] { 1,2,2 }, 2); 28 | assertEquals(1, actual[0]); 29 | assertEquals(2, actual[1]); 30 | } 31 | 32 | @Test 33 | public void testSearchRange4() { 34 | int[] actual = t.searchRange(new int[] { 0,0,1,1,1,4,5,5 }, 2); 35 | assertEquals(-1, actual[0]); 36 | assertEquals(-1, actual[1]); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/SearchInsertPositionTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.rules.ExpectedException; 8 | 9 | public class SearchInsertPositionTest { 10 | 11 | @Rule 12 | public ExpectedException thrown = ExpectedException.none(); 13 | 14 | private SearchInsertPosition t = new SearchInsertPosition(); 15 | 16 | @Test 17 | public void testSearchInsert() { 18 | assertEquals(2, t.searchInsert(new int[] { 1, 3, 5, 6 }, 5)); 19 | assertEquals(1, t.searchInsert(new int[] { 1, 3, 5, 6 }, 2)); 20 | assertEquals(4, t.searchInsert(new int[] { 1, 3, 5, 6 }, 7)); 21 | assertEquals(0, t.searchInsert(new int[] { 1, 3, 5, 6 }, 0)); 22 | } 23 | 24 | @Test 25 | public void testSearchInsert_zero() { 26 | assertEquals(0, t.searchInsert(new int[] {}, 5)); 27 | } 28 | 29 | @Test 30 | public void testSearchInsert_null() { 31 | thrown.expect(NullPointerException.class); 32 | t.searchInsert(null, 5); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/SetMatrixZeroesTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class SetMatrixZeroesTest { 8 | 9 | SetMatrixZeroes t = new SetMatrixZeroes(); 10 | 11 | @Test 12 | public void testSetZeroes2() { 13 | int[][] matrix = new int[][] { { 0, 1 } }; 14 | t.setZeroes2(matrix); 15 | assertArrayEquals(new int[] { 0, 0 }, matrix[0]); 16 | } 17 | 18 | @Test 19 | public void testSetZeroes3() { 20 | int[][] matrix = new int[][] { { -1 }, { 2 }, { 3 } }; 21 | t.setZeroes2(matrix); 22 | assertArrayEquals(new int[] { -1 }, matrix[0]); 23 | } 24 | 25 | @Test 26 | public void testSetZeroes() { 27 | int[][] matrix = new int[][] { { 0, 0, 0, 5 }, { 4, 3, 1, 4 }, 28 | { 0, 1, 1, 4 }, { 1, 2, 1, 3 }, { 0, 0, 1, 1 } }; 29 | t.setZeroes2(matrix); 30 | assertArrayEquals(new int[] { 0, 0, 0, 4 }, matrix[1]); 31 | assertArrayEquals(new int[] { 0, 0, 0, 3 }, matrix[3]); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/ShortestPalindromeTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class ShortestPalindromeTest { 8 | 9 | ShortestPalindrome s = new ShortestPalindrome(); 10 | 11 | @Test 12 | public void testShortestPalindrome() throws Exception { 13 | assertEquals("aba", s.shortestPalindrome("ba")); 14 | } 15 | } -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/SimplifyPathTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class SimplifyPathTest { 9 | 10 | SimplifyPath s = new SimplifyPath(); 11 | 12 | @Test 13 | public void testSimplifyPath() { 14 | assertEquals("/home", s.simplifyPath("/home/")); 15 | assertEquals("/c", s.simplifyPath("/a/./b/../../c/")); 16 | assertEquals("/", s.simplifyPath("/../")); 17 | assertEquals("/home/foo", s.simplifyPath("/home//foo/")); 18 | assertEquals("/", s.simplifyPath("/.")); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/SingleNumber2Test.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class SingleNumber2Test { 8 | 9 | SingleNumber2 t = new SingleNumber2(); 10 | 11 | @Test 12 | public void test() { 13 | assertEquals(5, t.singleNumber(new int[] { 1, 1, 5, 1 })); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/SortColorsTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class SortColorsTest { 9 | 10 | SortColors s = new SortColors(); 11 | 12 | @Test 13 | public void testSortColors() { 14 | int [] A = new int[]{1,2,0}; 15 | s.sortColors(A); 16 | assertEquals(0, A[0]); 17 | assertEquals(1, A[1]); 18 | assertEquals(2, A[2]); 19 | } 20 | 21 | @Test 22 | public void testSortColors2() { 23 | int [] A = new int[]{2,0,0}; 24 | s.sortColors(A); 25 | assertEquals(0, A[0]); 26 | assertEquals(0, A[1]); 27 | assertEquals(2, A[2]); 28 | } 29 | 30 | @Test 31 | public void testSortColorsTwoPass() { 32 | int [] A = new int[]{1,2,0}; 33 | s.sortColorsTwoPass(A); 34 | assertEquals(0, A[0]); 35 | assertEquals(1, A[1]); 36 | assertEquals(2, A[2]); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/SumRootToLeafNumbersTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import org.junit.Test; 6 | 7 | import com.pengyifan.leetcode.commons.TreeNode; 8 | 9 | public class SumRootToLeafNumbersTest { 10 | 11 | SumRootToLeafNumbers t = new SumRootToLeafNumbers(); 12 | 13 | @Test 14 | public void test() { 15 | TreeNode t1 = new TreeNode(1); 16 | TreeNode t2 = new TreeNode(2); 17 | TreeNode t3 = new TreeNode(3); 18 | t1.left = t2; 19 | t1.right = t3; 20 | assertEquals(25, t.sumNumbers(t1)); 21 | } 22 | 23 | @Test 24 | public void test_null() { 25 | assertEquals(0, t.sumNumbers(null)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/SurroundedRegionsTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class SurroundedRegionsTest { 9 | 10 | SurroundedRegions s = new SurroundedRegions(); 11 | 12 | @Test 13 | public void testSolve() { 14 | char[][] board = new char[][] { 15 | {'X', 'X', 'X', 'X'}, 16 | {'X', 'O', 'O', 'X'}, 17 | {'X', 'X', 'O', 'X'}, 18 | {'X', 'O', 'X', 'X'}, 19 | }; 20 | char[][] expected = new char[][] { 21 | {'X', 'X', 'X', 'X'}, 22 | {'X', 'X', 'X', 'X'}, 23 | {'X', 'X', 'X', 'X'}, 24 | {'X', 'O', 'X', 'X'}, 25 | }; 26 | s.solve(board); 27 | for (int i = 0; i < board.length; i++) { 28 | for (int j = 0; j < board[i].length; j++) { 29 | assertEquals(expected[i][j], board[i][j]); 30 | } 31 | } 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/ThreeSumTest.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 ThreeSumTest { 13 | 14 | ThreeSum t = new ThreeSum(); 15 | 16 | @Test 17 | public void test() { 18 | List> 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 dict = new HashSet(); 21 | for (String w : dictWords) { 22 | dict.add(w); 23 | } 24 | List solutions = wordBreak.wordBreak(s, dict); 25 | assertThat(solutions, hasItem("cats and dog")); 26 | assertThat(solutions, hasItem("cat sand dog")); 27 | } 28 | 29 | @Test 30 | public void testWordBreak2() { 31 | String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 32 | + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 33 | + "aaaaaaaaaaaaaaaaaaaaab"; 34 | String[] dictWords = new String[] { "a", "aa", "aaa", "aaaa", "aaaaa", 35 | "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa" }; 36 | Set dict = new HashSet(); 37 | for (String w : dictWords) { 38 | dict.add(w); 39 | } 40 | List solutions = wordBreak.wordBreak(s, dict); 41 | assertTrue(solutions.isEmpty()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/pengyifan/leetcode/WordPatternTest.java: -------------------------------------------------------------------------------- 1 | package com.pengyifan.leetcode; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class WordPatternTest { 8 | 9 | private WordPattern s = new WordPattern(); 10 | 11 | @Test 12 | public void testWordPattern() throws Exception { 13 | assertFalse(s.wordPattern("abba", "dog dog dog dog")); 14 | } 15 | 16 | @Test 17 | public void testWordPattern2() throws Exception { 18 | assertTrue(s.wordPattern("abba", "dog cat cat dog")); 19 | } 20 | 21 | @Test 22 | public void testWordPattern3() throws Exception { 23 | assertFalse(s.wordPattern("ab", "dog dog")); 24 | } 25 | } --------------------------------------------------------------------------------