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

LeetCode – Palindrome Pairs (Java)

Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. Example 1: Given words = [“bat”, “tab”, “cat”] Return [[0, 1], [1, 0]] The palindromes are [“battab”, “tabbat”] Java Solution public List<List<Integer>> … Read more

LeetCode – Reverse Linked List (Java)

Reverse a singly linked list. Java Solution 1 – Iterative public ListNode reverseList(ListNode head) { if(head==null||head.next==null) return head;   ListNode p1 = head; ListNode p2 = p1.next;   head.next = null; while(p1!=null&& p2!=null){ ListNode t = p2.next; p2.next = p1; p1 = p2; p2 = t; }   return p1; }public ListNode reverseList(ListNode head) { … Read more

LeetCode – Isomorphic Strings (Java)

Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. For example,”egg” and “add” are isomorphic, “foo” and “bar” are not. Java Solution 1 We can define a map which tracks the char-char mappings. If a value is already … Read more