LeetCode – Reverse Words in a String (Java)

Given an input string, reverse the string word by word. For example, given s = “the sky is blue”, return “blue is sky the”. Java Solution This problem is pretty straightforward. We first split the string to words array, and then iterate through the array and add each element to a new string. Note: StringBuilder … Read more

Reverse Double Linked List

Given a double linked list’s head node, reverse the list and return the new head node. Java Solution /* * For your reference: * * DoublyLinkedListNode { * int data; * DoublyLinkedListNode next; * DoublyLinkedListNode prev; * } * */ static DoublyLinkedListNode reverse(DoublyLinkedListNode head) { DoublyLinkedListNode p = head; DoublyLinkedListNode newHead = head;   while(p!=null){ … Read more

LeetCode – Subarray Sum Equals K (Java)

Given an array of integers and an integer k, find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Note that empty array is not considered as a subarray. Java Solution The sum problems can often be solved by using a hash map … Read more

LeetCode – Generate Parentheses (Java)

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: “((()))”, “(()())”, “(())()”, “()(())”, “()()()” Java Solution 1 – DFS This solution is simple and clear. In the dfs() method, left stands for the remaining number of (, right stands … Read more