LeetCode – Minimum Path Sum (Java)

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Java Solution 1: Depth-First Search A native solution would be depth-first search. It’s time is too expensive and fails the online judgement. public int minPathSum(int[][] grid) … Read more

LeetCode – Basic Calculator II (Java)

Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. You may assume that the given expression is always valid. Some examples: “3+2*2” = 7 Java Solution public int calculate(String s) { … Read more

LeetCode – PDF Update History (Java)

5/10/2016 1. Add about 20 more problems. 2. Optimize solutions for some old problems. 5/17/2016 1. Add 12 more problems. 2. Optimize solutions for some old problems. 3. Remove some naive solutions because they are too obvious and have no values. 8/1/2016 1. Add 30 more problems. 2. Optimize solutions for some old problems. 3. … Read more

LeetCode – Integer to English Words (Java)

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 – 1. For example, 123 -> “One Hundred Twenty Three” 12345 -> “Twelve Thousand Three Hundred Forty Five” Java Solution This problem is straightforward, but the corner cases should be considered carefully. public class Solution { HashMap<Integer, … Read more

LeetCode – Reverse Words in a String II (Java)

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. The input string does not contain leading or trailing spaces and the words are always separated by a single space. For example, Given s = “the sky is blue”, return “blue is sky the”. Could … Read more

LeetCode – Scramble String (Java)

Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. Java Solution public boolean isScramble(String s1, String s2) { if(s1.length()!=s2.length()) return false;   if(s1.length()==0 || s1.equals(s2)) return true;   char[] arr1 = s1.toCharArray(); char[] arr2 = s2.toCharArray(); Arrays.sort(arr1); Arrays.sort(arr2); if(!new String(arr1).equals(new String(arr2))){ return false; }   … Read more

LeetCode – One Edit Distance (Java)

Given two strings S and T, determine if they are both one edit distance apart. Java Solution public boolean isOneEditDistance(String s, String t) { if(s==null || t==null) return false;   int m = s.length(); int n = t.length();   if(Math.abs(m-n)>1){ return false; }   int i=0; int j=0; int count=0;   while(i<m&&j<n){ if(s.charAt(i)==t.charAt(j)){ i++; j++; … Read more