├── 2sum.go ├── 3SumClosest.go ├── 3sum.go ├── 4sum.go ├── ListNode.java ├── MergeTowSortList.java ├── README.md ├── addBinary.go ├── addDigit.go ├── combinationSum.go ├── containerWithMostWater.go ├── generateParentheses.go ├── groupAnagrams.go ├── integerToRoman.go ├── letterCombinationsOfAPhoneNumber.go ├── longestCommonPrefix.go ├── longestSubstringWithoutRepeatingCharacters.go ├── longestValidParentheses.go ├── mergeKSortedLists.go ├── nextPermutation.go ├── nthUglyNumber.go ├── regularExpressionMatching.go ├── removeDuplicatesFromSortedArray.go ├── removeNthNodeFromEndOfList.go ├── reverseInt.go ├── reverseNodesInKGroup.go ├── romanToInteger.go ├── searchForRange.go ├── searchInRotatedSortedArray.go ├── searchInsert.go ├── skylineProblem.go ├── strStr.go ├── stringToIntegerAtoi.go ├── substringWithConcatenationOfAllWords.go ├── swapNodesInPairs.go ├── symmetricTree.go ├── testJustification.go ├── trappingRainWater.go ├── triangle.go ├── uglyNumber.go ├── uniqueBSTII.go ├── uniquePath.go ├── validNumber.go ├── validPalindrome.go ├── validParentheses.go ├── validSudoku.go ├── validateBinarySearchTree.go ├── wildcardMatching.go ├── wordBreakI.go ├── wordLadder.go ├── wordPattern.go ├── wordSearch.go └── zigzag.go /2sum.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/two-sum/ 2 | // Author : 18plusui 3 | // Date : 2016-03-10 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array of integers, find two numbers such that they add up to a specific target number. 8 | * 9 | * The function twoSum should return indices of the two numbers such that they add up to the target, 10 | * where index1 must be less than index2. Please note that your returned answers (both index1 and index2) 11 | * are not zero-based. 12 | * 13 | * You may assume that each input would have exactly one solution. 14 | * 15 | * Input: numbers={2, 7, 11, 15}, target=9 16 | * Output: index1=1, index2=2 17 | * 18 | **********************************************************************************/ 19 | 20 | package leetcode 21 | 22 | func twoSum(nums []int, target int) []int { 23 | var result []int 24 | 25 | numslen := len(nums) 26 | for i := 0; i < numslen; i++ { 27 | for j := i + 1; j < numslen; j++ { 28 | if target-nums[i] == nums[j] { 29 | 30 | result = append(result, i) 31 | result = append(result, j) 32 | 33 | return result 34 | } 35 | 36 | } 37 | } 38 | return result 39 | } 40 | -------------------------------------------------------------------------------- /3SumClosest.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/3sum-closest/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array S of n integers, find three integers in S such that the sum is 8 | * closest to a given number, target. Return the sum of the three integers. 9 | * You may assume that each input would have exactly one solution. 10 | * 11 | * For example, given array S = {-1 2 1 -4}, and target = 1. 12 | * 13 | * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 14 | * 15 | * 16 | **********************************************************************************/ 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "sort" 22 | "sync/atomic" 23 | ) 24 | 25 | var maxInt int = 2147483647 26 | var arrLen int 27 | var ops uint64 = 0 28 | var sortArr []int 29 | 30 | func cal(inputArr []int, target int) { 31 | 32 | //make sure are sorted 33 | if !sort.IntsAreSorted(inputArr) { 34 | // sort inputArr 35 | sort.Ints(inputArr) 36 | fmt.Println(inputArr) 37 | sortArr = inputArr 38 | } 39 | 40 | //get this array length 41 | arrLen = len(sortArr) 42 | 43 | for i := 0; i < arrLen-2; i++ { 44 | fmt.Println("loop time : ", i) 45 | if i > 0 && sortArr[i-1] == sortArr[i] { 46 | fmt.Println("I'm come in") 47 | continue 48 | } 49 | 50 | currNum := sortArr[i] 51 | 52 | low := i + 1 53 | high := arrLen - 1 54 | 55 | for low < high { 56 | lowNum := sortArr[low] 57 | highNum := sortArr[high] 58 | sumNum := currNum + lowNum + highNum 59 | 60 | if sumNum-target == 0 { 61 | printer(currNum, lowNum, highNum, target) 62 | low++ 63 | 64 | } else { 65 | 66 | if abs(sumNum) < maxInt { 67 | 68 | maxInt = abs(sumNum) 69 | printer(currNum, lowNum, highNum, sumNum) 70 | 71 | } 72 | 73 | if sumNum-target > 0 { 74 | 75 | for high > 0 && sortArr[high] == sortArr[high-1] { 76 | high-- 77 | } 78 | 79 | high-- 80 | } else { 81 | 82 | for low < arrLen && sortArr[low] == sortArr[low+1] { 83 | low++ 84 | } 85 | 86 | low++ 87 | } 88 | 89 | } 90 | } 91 | } 92 | } 93 | 94 | func printer(currNum int, lowNum int, highNum int, target int) { 95 | atomic.AddUint64(&ops, 1) 96 | opsFinal := atomic.LoadUint64(&ops) 97 | fmt.Println("--------------Begin--------------") 98 | fmt.Println("counter : ", opsFinal) 99 | fmt.Println("first Number : ", currNum, " , ", lowNum, " , ", highNum) 100 | fmt.Println("target : ", target) 101 | fmt.Println("---------------End---------------") 102 | fmt.Println("") 103 | } 104 | 105 | func abs(sn int) int { 106 | if sn > 0 { 107 | return sn 108 | } 109 | 110 | return -sn 111 | } 112 | 113 | func main() { 114 | cal([]int{-4, -2, 0, -8, -11, 3, 6, 7}, 0) 115 | fmt.Println("the last Max Int number is : ", maxInt) 116 | } 117 | -------------------------------------------------------------------------------- /3sum.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/3sum/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? 8 | * Find all unique triplets in the array which gives the sum of zero. 9 | * 10 | * Note: 11 | * 12 | * Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) 13 | * The solution set must not contain duplicate triplets. 14 | * 15 | * For example, given array S = {-1 0 1 2 -1 -4}, 16 | * 17 | * A solution set is: 18 | * (-1, 0, 1) 19 | * (-1, -1, 2) 20 | * 21 | * 22 | **********************************************************************************/ 23 | package main 24 | 25 | import ( 26 | "fmt" 27 | "sort" 28 | "sync/atomic" 29 | ) 30 | 31 | var arrLen int 32 | var ops uint64 = 0 33 | var sortArr []int 34 | 35 | func getArr() []int { 36 | inputArr := []int{-7, -8, -1, -2, -4, 1, 4, 9, 3, 6} 37 | return inputArr 38 | } 39 | 40 | func cal() { 41 | // call get array func 42 | inputArr := getArr() 43 | 44 | //make sure are sorted 45 | fmt.Println(inputArr) 46 | if !sort.IntsAreSorted(inputArr) { 47 | // sort inputArr 48 | sort.Ints(inputArr) 49 | fmt.Println(inputArr) 50 | sortArr = inputArr 51 | } 52 | 53 | //get this array length 54 | arrLen = len(sortArr) 55 | 56 | for i := 0; i < arrLen-2; i++ { 57 | fmt.Println("loop time : ", i) 58 | if i > 0 && sortArr[i-1] == sortArr[i] { 59 | //if near equal ,skip this time loop 60 | continue 61 | } 62 | 63 | currNum := sortArr[i] 64 | 65 | low := i + 1 66 | high := arrLen - 1 67 | 68 | for low < high { 69 | lowNum := sortArr[low] 70 | highNum := sortArr[high] 71 | 72 | sumNum := currNum + lowNum + highNum 73 | 74 | if sumNum == 0 { 75 | //2d array use 76 | atomic.AddUint64(&ops, 1) 77 | opsFinal := atomic.LoadUint64(&ops) 78 | 79 | //print result 80 | fmt.Println("--------------Begin--------------") 81 | fmt.Println("counter : ", opsFinal) 82 | fmt.Println("first Number : ", currNum) 83 | fmt.Println("second Number : ", lowNum) 84 | fmt.Println("third Number : ", highNum) 85 | fmt.Println("---------------End---------------") 86 | fmt.Println("") 87 | 88 | low++ 89 | 90 | } else if sumNum > 0 { 91 | 92 | for high > 0 && sortArr[high] == sortArr[high-1] { 93 | high-- 94 | } 95 | 96 | high-- 97 | 98 | } else { 99 | 100 | for low < arrLen && sortArr[low] == sortArr[low+1] { 101 | 102 | low++ 103 | } 104 | low++ 105 | } 106 | 107 | } 108 | } 109 | 110 | } 111 | 112 | func main() { 113 | 114 | cal() 115 | 116 | } 117 | -------------------------------------------------------------------------------- /4sum.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/4sum/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? 8 | * Find all unique quadruplets in the array which gives the sum of target. 9 | * 10 | * Note: 11 | * 12 | * Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) 13 | * The solution set must not contain duplicate quadruplets. 14 | * 15 | * For example, given array S = {1 0 -1 0 -2 2}, and target = 0. 16 | * 17 | * A solution set is: 18 | * (-1, 0, 0, 1) 19 | * (-2, -1, 1, 2) 20 | * (-2, 0, 0, 2) 21 | * 22 | * 23 | **********************************************************************************/ 24 | package main 25 | 26 | import ( 27 | "fmt" 28 | "sort" 29 | "sync/atomic" 30 | ) 31 | 32 | var inputArr []int 33 | var arrLen int 34 | var ops uint64 = 0 35 | var sortArr []int 36 | var resNum [4]int 37 | 38 | func threeSum(inputArr []int, target int, currInput int) []int { 39 | 40 | if !sort.IntsAreSorted(inputArr) { 41 | // sort inputArr 42 | sort.Ints(inputArr) 43 | // fmt.Println(inputArr) 44 | sortArr = inputArr 45 | } 46 | 47 | //get this array length 48 | arrLen = len(sortArr) 49 | 50 | for i := 0; i < arrLen-2; i++ { 51 | // fmt.Println("loop time : ", i) 52 | if i > 0 && sortArr[i-1] == sortArr[i] { 53 | //if near equal ,skip this time loop 54 | continue 55 | } 56 | 57 | currNum := sortArr[i] 58 | 59 | low := i + 1 60 | high := arrLen - 1 61 | 62 | for low < high { 63 | lowNum := sortArr[low] 64 | highNum := sortArr[high] 65 | 66 | sumNum := currNum + lowNum + highNum 67 | 68 | if sumNum == target { 69 | resNum[0] = currNum 70 | resNum[1] = lowNum 71 | resNum[2] = highNum 72 | resNum[3] = currInput 73 | printer(resNum, target) 74 | low++ 75 | 76 | } else if sumNum > 0 { 77 | 78 | for high > 0 && sortArr[high] == sortArr[high-1] { 79 | high-- 80 | } 81 | 82 | high-- 83 | 84 | } else { 85 | 86 | for low < arrLen && sortArr[low] == sortArr[low+1] { 87 | 88 | low++ 89 | } 90 | low++ 91 | } 92 | 93 | } 94 | } 95 | 96 | return inputArr 97 | } 98 | 99 | func fourSum(inputArr []int, target int) { 100 | if len(inputArr) <= 4 { 101 | // printer(currNum, lowNum, highNum, target) 102 | } 103 | 104 | for i := 0; i < len(inputArr)-3; i++ { 105 | 106 | if i > 0 && inputArr[i-1] == inputArr[i] { 107 | continue 108 | } 109 | 110 | threeSum(inputArr[i+1:len(inputArr)], target-inputArr[i], inputArr[i]) 111 | 112 | } 113 | 114 | } 115 | 116 | func printer(resNum [4]int, target int) { 117 | atomic.AddUint64(&ops, 1) 118 | opsFinal := atomic.LoadUint64(&ops) 119 | fmt.Println("--------------Begin--------------") 120 | fmt.Println("Math time : ", opsFinal) 121 | fmt.Println("result set is : ", resNum[0], " , ", resNum[1], " , ", resNum[2], " , ", resNum[3]) 122 | fmt.Println("---------------End---------------") 123 | fmt.Println("") 124 | } 125 | 126 | func main() { 127 | inputArr = []int{1, 2, 4, 6, 9, -1, -2, -5, -8, 0} 128 | fourSum(inputArr, 0) 129 | 130 | } 131 | -------------------------------------------------------------------------------- /ListNode.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.Random; 4 | 5 | // Definition for singly-linked list. 6 | public class ListNode { 7 | int val; 8 | ListNode next; 9 | 10 | ListNode(int x) { 11 | val = x; 12 | next = null; 13 | } 14 | 15 | public ListNode createListNode(int i, ListNode ln) { 16 | 17 | Random r = new Random(); 18 | int val = r.nextInt(10); 19 | 20 | ln.next = new ListNode(val); 21 | 22 | if (i == 0) { 23 | return ln; 24 | } 25 | i--; 26 | createListNode(i, ln.next); 27 | return ln.next; 28 | } 29 | 30 | public static void main(String[] args) { 31 | 32 | ListNode listnode = new ListNode(0); 33 | 34 | ListNode result = listnode.createListNode(10, listnode); 35 | 36 | System.out.println(result.next.val + " : " + result.val); 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MergeTowSortList.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | public class MergeTowSortList { 4 | 5 | public ListNode merge2List(ListNode a, ListNode b) { 6 | 7 | ListNode result = new ListNode(0); 8 | ListNode h = result; 9 | while (a != null && b != null) { 10 | if (a.val < b.val) { 11 | result.next = a; 12 | a = a.next; 13 | } else { 14 | result.next = b; 15 | b = b.next; 16 | } 17 | result = result.next; 18 | 19 | } 20 | 21 | if (a != null) 22 | result.next = a; 23 | else 24 | result.next = b; 25 | 26 | return h; 27 | 28 | } 29 | 30 | public static void main(String[] args) { 31 | ListNode ln = new ListNode(0); 32 | 33 | ListNode l1 = ln.createListNode(10, ln); 34 | ListNode l2 = ln.createListNode(10, ln); 35 | 36 | MergeTowSortList mtsl = new MergeTowSortList(); 37 | 38 | ListNode rst = mtsl.merge2List(l1.next, l2.next); 39 | 40 | while (rst != null) { 41 | System.out.println("rst : " + rst.val); 42 | rst = rst.next; 43 | 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # leetcode 2 | do something for myself 3 | 4 | welcome 5 | -------------------------------------------------------------------------------- /addBinary.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/add-binary/ 2 | // Author : 18plusui 3 | // Date : 2016-04-02 4 | 5 | /********************************************************************************** 6 | * 7 | * Given two binary strings, return their sum (also a binary string). 8 | * 9 | * For example, 10 | * a = "11" 11 | * b = "1" 12 | * Return "100". 13 | * 14 | * 15 | **********************************************************************************/ 16 | package main 17 | 18 | import ( 19 | "fmt" 20 | "strconv" 21 | ) 22 | 23 | func addBinary(a, b string) { 24 | var alen, blen int = len(a), len(b) 25 | var plus bool 26 | var add string 27 | var result string 28 | 29 | for alen > 0 || blen > 0 { 30 | 31 | var ha int = threeCul(a, alen) 32 | var hb int = threeCul(b, blen) 33 | var hc int 34 | if plus { 35 | hc = 1 36 | } else { 37 | hc = 0 38 | } 39 | 40 | if ha+hb+hc == 3 { 41 | 42 | plus = true 43 | add = "1" 44 | 45 | } else if ha+hb+hc == 2 { 46 | 47 | add = "0" 48 | plus = true 49 | 50 | } else { 51 | add = strconv.Itoa(ha + hb + hc) 52 | plus = false 53 | } 54 | 55 | result += add 56 | 57 | alen-- 58 | blen-- 59 | 60 | } 61 | if plus { 62 | result += "1" 63 | } 64 | 65 | printReslut(result) 66 | 67 | } 68 | 69 | func threeCul(val string, index int) int { 70 | if index <= 0 { 71 | return 0 72 | } 73 | retInt, _ := strconv.Atoi(val[index-1 : index]) 74 | return retInt 75 | } 76 | 77 | func printReslut(s string) { 78 | 79 | runes := []rune(s) 80 | for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { 81 | runes[i], runes[j] = runes[j], runes[i] 82 | } 83 | fmt.Println(string(runes)) 84 | 85 | } 86 | 87 | func main() { 88 | a := "11" 89 | b := "1" 90 | addBinary(a, b) 91 | } 92 | -------------------------------------------------------------------------------- /addDigit.go: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/add-digits/ 2 | // Author : 18plusui 3 | // Date : 2016-04-3 4 | 5 | /********************************************************************************** 6 | * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 7 | * 8 | * For example: 9 | * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 10 | * 11 | * Follow up: 12 | * Could you do it without any loop/recursion in O(1) runtime? 13 | * 14 | **********************************************************************************/ 15 | package main 16 | 17 | import ( 18 | "fmt" 19 | ) 20 | 21 | func addDigit(num int) int { 22 | for num > 9 { 23 | num = num/10 + num%10 24 | } 25 | return num 26 | } 27 | 28 | func main() { 29 | 30 | fmt.Print(addDigit(101)) 31 | 32 | } 33 | -------------------------------------------------------------------------------- /combinationSum.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/combination-sum/ 2 | // Author : 18plusui 3 | // Date : 2016-04-28 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a set of candidate numbers (C) and a target number (T), find all unique combinations 8 | * in C where the candidate numbers sums to T. 9 | * 10 | * The same repeated number may be chosen from C unlimited number of times. 11 | * 12 | * Note: 13 | * 14 | * All numbers (including target) will be positive integers. 15 | * Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 16 | * The solution set must not contain duplicate combinations. 17 | * 18 | * For example, given candidate set 2,3,6,7 and target 7, 19 | * A solution set is: 20 | * [7] 21 | * [2, 2, 3] 22 | * 23 | **********************************************************************************/ 24 | package main 25 | 26 | import ( 27 | "fmt" 28 | "sort" 29 | ) 30 | 31 | func combinationSumHelper(candidates []int, start, target int, solution []int, result [][]int) { 32 | if target < 0 { 33 | return 34 | } 35 | 36 | if target == 0 { 37 | result = append(result, solution) 38 | fmt.Println(solution) 39 | return 40 | } 41 | 42 | for i := start; i < len(candidates); i++ { 43 | if i > start && candidates[i] == candidates[i-1] { 44 | continue 45 | } 46 | 47 | solution = append(solution, candidates[i]) 48 | combinationSumHelper(candidates, i, target-candidates[i], solution, result) 49 | 50 | solution = solution[:len(solution)-1] 51 | 52 | } 53 | 54 | } 55 | 56 | func combinationSum(candidates []int, target int) { 57 | var result [][]int 58 | if len(candidates) <= 0 { 59 | return 60 | } 61 | 62 | sort.IntsAreSorted(candidates) 63 | var solution []int 64 | combinationSumHelper(candidates, 0, target, solution, result) 65 | 66 | } 67 | 68 | func main() { 69 | combinationSum([]int{1, 3, 2, 4, 5, 6}, 7) 70 | } 71 | -------------------------------------------------------------------------------- /containerWithMostWater.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/container-with-most-water/ 2 | // Author : 18plusui 3 | // Date : 2016-04-11 4 | 5 | /********************************************************************************** 6 | * 7 | * Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). 8 | * n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 9 | * 10 | * Find two lines, which together with x-axis forms a container, such that the container contains the most water. 11 | * 12 | * Note: You may not slant the container. 13 | * 14 | **********************************************************************************/ 15 | 16 | package main 17 | 18 | import ( 19 | "fmt" 20 | ) 21 | 22 | func maxArea(height []int) int { 23 | var maxarea,left,right,area int = 0,0,len(height)-1,0 24 | 25 | for left < right{ 26 | 27 | area = (right - left) * calu3(height[left], height[right]) 28 | maxarea = calu3(area, maxarea) 29 | 30 | if height[left] < height[right] { 31 | 32 | left++ 33 | 34 | for left < right && height[left-1] >= height[left] { 35 | left++ 36 | } 37 | 38 | } else { 39 | 40 | right-- 41 | 42 | for right > left && height[right+1] >= height[right] { 43 | right-- 44 | } 45 | 46 | } 47 | } 48 | 49 | return maxarea 50 | 51 | } 52 | 53 | func calu3(a,b int) int { 54 | if a > b { 55 | return a 56 | } else { 57 | return b 58 | } 59 | } 60 | 61 | func main() { 62 | inputArr := []int{1,2,6,5,2,1} 63 | fmt.Print(maxArea(inputArr)) 64 | 65 | } -------------------------------------------------------------------------------- /generateParentheses.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/generate-parentheses/ 2 | // Author : 18plusui 3 | // Date : 2016-04-17 4 | 5 | /********************************************************************************** 6 | * 7 | * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 8 | * 9 | * For example, given n = 3, a solution set is: 10 | * 11 | * "((()))", "(()())", "(())()", "()(())", "()()()" 12 | * 13 | **********************************************************************************/ 14 | 15 | package main 16 | 17 | import ( 18 | "fmt" 19 | ) 20 | 21 | func generator(result []string, left int, right int, s string) { 22 | if left == 0 && right == 0 { 23 | result = append(result, s) 24 | fmt.Println(result) 25 | } 26 | 27 | if left > 0 { 28 | generator(result, left-1, right, s+"(") 29 | } 30 | 31 | if right > 0 && right > left { 32 | generator(result, left, right-1, s+")") 33 | } 34 | } 35 | 36 | func generatorParenthesis(n int) { 37 | var result []string 38 | var s string 39 | generator(result, n, n, s) 40 | } 41 | 42 | func main() { 43 | generatorParenthesis(3) 44 | } 45 | -------------------------------------------------------------------------------- /groupAnagrams.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/anagrams/ 2 | // Author : 18plusui 3 | // Date : 2016-06-04 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array of strings, group anagrams together. 8 | * 9 | * For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 10 | * Return: 11 | * 12 | * [ 13 | * ["ate", "eat","tea"], 14 | * ["nat","tan"], 15 | * ["bat"] 16 | * ] 17 | * 18 | * Note: 19 | * 20 | * For the return value, each inner list's elements must follow the lexicographic order. 21 | * All inputs will be in lower-case. 22 | * 23 | **********************************************************************************/ 24 | 25 | package main 26 | 27 | import ( 28 | "fmt" 29 | "sort" 30 | ) 31 | 32 | type sortRunes []rune 33 | 34 | func (s sortRunes) Less(i, j int) bool { 35 | return s[i] < s[j] 36 | } 37 | 38 | func (s sortRunes) Swap(i, j int) { 39 | s[i], s[j] = s[j], s[i] 40 | } 41 | 42 | func (s sortRunes) Len() int { 43 | return len(s) 44 | } 45 | 46 | func SortString(s string) string { 47 | r := []rune(s) 48 | sort.Sort(sortRunes(r)) 49 | return string(r) 50 | } 51 | 52 | func groupAnagrams(strs []string) [][]string { 53 | 54 | strlen := len(strs) 55 | result := make([][]string, strlen) 56 | m := make(map[string]int) 57 | var i, j int 58 | 59 | for i, j = 0, 0; i < strlen; i++ { 60 | word := strs[i] 61 | sortword := SortString(word) 62 | 63 | if val, ok := m[sortword]; ok { 64 | result[val] = append(result[val], word) 65 | } else { 66 | m[sortword] = j 67 | result[j] = append(result[j], word) 68 | j++ 69 | } 70 | 71 | } 72 | 73 | return result[0:j] 74 | } 75 | 76 | func main() { 77 | 78 | strs := []string{"eat", "tea", "tan", "ate", "nat", "bat"} 79 | 80 | fmt.Println(groupAnagrams(strs)) 81 | } 82 | -------------------------------------------------------------------------------- /integerToRoman.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/integer-to-roman/ 2 | // Author : 18plusui 3 | // Date : 2016-04-12 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an integer, convert it to a roman numeral. 8 | * 9 | * Input is guaranteed to be within the range from 1 to 3999. 10 | * 11 | **********************************************************************************/ 12 | package main 13 | 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | func intToRoman(num int) string { 19 | 20 | symbol := []string{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"} 21 | value := []int{1000 ,900 ,500 ,400 , 100, 90, 50, 40, 10, 9, 5, 4, 1} 22 | var result string 23 | 24 | for i := 0; num !=0; i++ { 25 | 26 | for num >= value[i] { 27 | num -= value[i] 28 | result += symbol[i] 29 | } 30 | } 31 | 32 | return result 33 | } 34 | 35 | func main() { 36 | fmt.Println(intToRoman(10)) 37 | } -------------------------------------------------------------------------------- /letterCombinationsOfAPhoneNumber.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ 2 | // Author : 18plusui 3 | // Date : 2016-04-13 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a digit string, return all possible letter combinations that the number could represent. 8 | * 9 | * A mapping of digit to letters (just like on the telephone buttons) is given below. 10 | * 11 | * Input:Digit string "23" 12 | * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 13 | * 14 | * Note: 15 | * Although the above answer is in lexicographical order, your answer could be in any order you want. 16 | * 17 | **********************************************************************************/ 18 | package main 19 | 20 | import ( 21 | "fmt" 22 | "unicode" 23 | "strconv" 24 | ) 25 | 26 | func letterCombinations(str string) []string { 27 | match := [][]string{{" ","","",""}, //0 28 | {"","","",""}, //1 29 | {"a","b","c",""},//2 30 | {"d","e","f",""},//3 31 | {"g","h","i",""},//4 32 | {"j","k","l",""},//5 33 | {"m","n","o",""},//6 34 | {"p","q","r","s"},//7 35 | {"t","u","v",""},//8 36 | {"w","x","y","z"},//9 37 | } 38 | 39 | var result []string 40 | if len(str) <= 0 { 41 | 42 | return append(result,"") 43 | } 44 | 45 | for i := 0; i < len(str); i++ { 46 | if !unicode.IsDigit(rune(str[i])) { 47 | return []string{""} 48 | } 49 | 50 | d,_ := strconv.Atoi(string(str[i])) 51 | 52 | if len(result) <= 0 { 53 | for j := 0; j < 4 && match[d][j]!=""; j++ { 54 | result = append(result , match[d][j]) 55 | 56 | } 57 | continue 58 | } 59 | 60 | var r []string 61 | for z := 0; z < len(result); z++ { 62 | 63 | for k := 0; k < 4 && match[d][k]!=""; k++ { 64 | r = append(r,result[z]+match[d][k]) 65 | 66 | } 67 | 68 | } 69 | result = r 70 | } 71 | 72 | return result 73 | } 74 | 75 | func main() { 76 | fmt.Println(letterCombinations("23")) 77 | } 78 | -------------------------------------------------------------------------------- /longestCommonPrefix.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/longest-common-prefix/ 2 | // Author : 18plusui 3 | // Date : 2016-04-13 4 | 5 | /********************************************************************************** 6 | * 7 | * Write a function to find the longest common prefix string amongst an array of strings. 8 | * 9 | **********************************************************************************/ 10 | 11 | package main 12 | 13 | import ( 14 | "fmt" 15 | ) 16 | 17 | func longestPrefix (strs []string) string { 18 | var word string 19 | if len(strs) <= 0 { return word } 20 | for i := 1; i <= len(strs[0]); i++ { 21 | w := (strs[0])[:i] 22 | match := true 23 | for j := 1; j < len(strs); j++ { 24 | if i > len(strs[j]) || w != (strs[j])[:i] { 25 | match = false 26 | break 27 | } 28 | } 29 | if !match { 30 | return word 31 | } 32 | word = w 33 | 34 | } 35 | return word 36 | } 37 | 38 | func main() { 39 | s := []string{"abab"} 40 | fmt.Println(longestPrefix(s)) 41 | } 42 | -------------------------------------------------------------------------------- /longestSubstringWithoutRepeatingCharacters.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ 2 | // Author : 18plusui 3 | // Date : 2016-04-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a string, find the length of the longest substring without repeating characters. 8 | * For example, the longest substring without repeating letters for "abcabcbb" is "abc", 9 | * which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. 10 | * 11 | **********************************************************************************/ 12 | 13 | package main 14 | 15 | import ( 16 | "fmt" 17 | ) 18 | 19 | func lengthOfLongestSubstring(s string) int { 20 | 21 | m := make(map[string]int) 22 | var maxLen int 23 | var lastRepeatPos int = 0 24 | 25 | for i := 0; i < len(s); i++ { 26 | 27 | if _, ok := m[string(s[i])]; ok && lastRepeatPos < m[string(s[i])] { 28 | fmt.Println("lastPos : ", m[string(s[i])]) 29 | lastRepeatPos = m[string(s[i])] 30 | continue 31 | } 32 | 33 | if _, ok := m[string(s[i])]; !ok { 34 | m[string(s[i])] = i 35 | } 36 | 37 | fmt.Println("map : ", m) 38 | 39 | } 40 | 41 | if lastRepeatPos == 0 { 42 | maxLen = 1 43 | } else { 44 | maxLen = lastRepeatPos + 1 45 | } 46 | return maxLen 47 | } 48 | 49 | func main() { 50 | fmt.Println(lengthOfLongestSubstring("")) 51 | fmt.Println(lengthOfLongestSubstring("a")) 52 | fmt.Println(lengthOfLongestSubstring("au")) 53 | fmt.Println(lengthOfLongestSubstring("bbbbb")) 54 | fmt.Println(lengthOfLongestSubstring("abcdabcdbb")) 55 | } 56 | -------------------------------------------------------------------------------- /longestValidParentheses.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/longest-valid-parentheses/ 2 | // Author : Hao Chen 3 | // Date : 2014-07-18 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a string containing just the characters '(' and ')', 8 | * find the length of the longest valid (well-formed) parentheses substring. 9 | * 10 | * For "(()", the longest valid parentheses substring is "()", which has length = 2. 11 | * 12 | * Another example is ")()())", where the longest valid parentheses substring is "()()", 13 | * which has length = 4. 14 | * 15 | **********************************************************************************/ 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | ) 22 | 23 | func longestValidParentheses(s string) int { 24 | var maxlen int 25 | lastError := -1 26 | var stack []int 27 | for i := 0; i < len(s); i++ { 28 | if s[i] == '(' { 29 | stack = append(stack, i) 30 | } else if s[i] == ')' { 31 | if len(stack) > 0 { 32 | stack = stack[:len(stack)-1] 33 | length := 0 34 | if len(stack) == 0 { 35 | length = i - lastError 36 | } else { 37 | length = i - stack[len(stack)-1] 38 | } 39 | if length > maxlen { 40 | maxlen = length 41 | } 42 | } else { 43 | lastError = i 44 | } 45 | } 46 | } 47 | return maxlen 48 | } 49 | 50 | func main() { 51 | fmt.Println(longestValidParentheses(")()())")) 52 | } 53 | -------------------------------------------------------------------------------- /mergeKSortedLists.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/merge-k-sorted-lists/ 2 | // Author : 18plusui 3 | // Date : 2016-04-23 4 | 5 | /********************************************************************************** 6 | * 7 | * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 8 | * 9 | ***********************************************************************************/ 10 | 11 | package main 12 | 13 | import ( 14 | "fmt" 15 | ) 16 | 17 | func mergeKLists(lists []*ListNode) *ListNode { 18 | dummy := new(ListNode) 19 | curr := dummy 20 | 21 | length := len(lists) 22 | for { 23 | minPos := -1 24 | for i := 0; i < length; i++ { 25 | if lists[i] != nil && (minPos == -1 || lists[minPos].Val > lists[i].Val) { 26 | minPos = i 27 | } 28 | } 29 | if minPos == -1 { 30 | break 31 | } 32 | curr.Next = lists[minPos] 33 | lists[minPos] = lists[minPos].Next 34 | curr = curr.Next 35 | } 36 | 37 | return dummy.Next 38 | } 39 | 40 | type ListNode struct { 41 | Val int 42 | Next *ListNode 43 | } 44 | 45 | func (l *ListNode) setVal(val int) *ListNode { 46 | l.Val = val 47 | l.Next = nil 48 | return l 49 | } 50 | 51 | func createList(intSlice []int, ln *ListNode) *ListNode { 52 | n := len(intSlice) 53 | head := new(ListNode) 54 | 55 | if n != 0 { 56 | val := intSlice[n-1] 57 | ln.Next = head.setVal(val) 58 | } else { 59 | return ln 60 | } 61 | 62 | n-- 63 | 64 | createList(intSlice[:n], ln.Next) 65 | return ln.Next 66 | } 67 | 68 | func printList(list *ListNode) { 69 | for list != nil { 70 | fmt.Println("===", list.Val) 71 | list = list.Next 72 | 73 | } 74 | } 75 | 76 | func main() { 77 | a := []int{3, 3, 3, 2, 1} 78 | 79 | la := new(ListNode) 80 | la = createList(a, la) 81 | 82 | b := []int{5, 4, 3, 2, 1} 83 | 84 | lb := new(ListNode) 85 | lb = createList(b, lb) 86 | 87 | var lns []*ListNode 88 | lns = append(lns, la) 89 | lns = append(lns, lb) 90 | 91 | ln := mergeKLists(lns) 92 | printList(ln) 93 | } 94 | 95 | import ( 96 | "container/heap" 97 | "fmt" 98 | ) 99 | 100 | type Item struct { 101 | value int 102 | priority int 103 | index int 104 | } 105 | 106 | type PriorityQueue []*Item 107 | 108 | func (pq PriorityQueue) Len() int { return len(pq) } 109 | 110 | func (pq PriorityQueue) Less(i, j int) bool { 111 | 112 | return pq[i].priority < pq[j].priority 113 | } 114 | 115 | func (pq PriorityQueue) Swap(i, j int) { 116 | pq[i], pq[j] = pq[j], pq[i] 117 | pq[i].index = i 118 | pq[j].index = j 119 | } 120 | 121 | func (pq *PriorityQueue) Push(x interface{}) { 122 | n := len(*pq) 123 | item := x.(*Item) 124 | item.index = n 125 | *pq = append(*pq, item) 126 | } 127 | 128 | func (pq *PriorityQueue) Pop() interface{} { 129 | old := *pq 130 | n := len(old) 131 | item := old[n-1] 132 | item.index = -1 133 | *pq = old[0 : n-1] 134 | return item 135 | } 136 | 137 | func (pq *PriorityQueue) update(item *Item, value int, priority int) { 138 | item.value = value 139 | item.priority = priority 140 | heap.Fix(pq, item.index) 141 | } 142 | 143 | func main() { 144 | list1 := []int{1, 2, 3, 4, 6} 145 | list2 := []int{1, 2, 3, 7, 6} 146 | pq := make(PriorityQueue, len(list1)) 147 | i := 0 148 | for priority, value := range list1 { 149 | pq[i] = &Item{ 150 | value: value, 151 | priority: priority, 152 | index: i, 153 | } 154 | i++ 155 | } 156 | heap.Init(&pq) 157 | 158 | for priority, value := range list2 { 159 | 160 | item := &Item{ 161 | value: value, 162 | priority: priority, 163 | } 164 | heap.Push(&pq, item) 165 | } 166 | 167 | for pq.Len() > 0 { 168 | item := heap.Pop(&pq).(*Item) 169 | fmt.Print(item.value) 170 | } 171 | } 172 | 173 | -------------------------------------------------------------------------------- /nextPermutation.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/next-permutation/ 2 | // Author : 18plusui 3 | // Date : 2016-04-27 4 | 5 | /********************************************************************************** 6 | * 7 | * Implement next permutation, which rearranges numbers into the lexicographically next 8 | * greater permutation of numbers. 9 | * 10 | * If such arrangement is not possible, it must rearrange it as the lowest possible order 11 | * (ie, sorted in ascending order). 12 | * 13 | * The replacement must be in-place, do not allocate extra memory. 14 | * 15 | * Here are some examples. Inputs are in the left-hand column and its corresponding outputs 16 | * are in the right-hand column. 17 | * 18 | * 1,2,3 → 1,3,2 19 | * 3,2,1 → 1,2,3 20 | * 1,1,5 → 1,5,1 21 | * 22 | **********************************************************************************/ 23 | 24 | package main 25 | 26 | import ( 27 | "fmt" 28 | ) 29 | 30 | func nextPermutation(num []int) { 31 | if len(num) <= 1 { 32 | return 33 | } 34 | 35 | for i := len(num) - 1; i > 0; i-- { 36 | if num[i-1] < num[i] { 37 | j := len(num) - 1 38 | for num[i-1] >= num[j] { 39 | j-- 40 | } 41 | 42 | num[j], num[i-1] = num[i-1], num[j] 43 | reverse(num[i:]) 44 | fmt.Println(num) 45 | return 46 | } 47 | 48 | if i == 1 { 49 | return 50 | } 51 | } 52 | 53 | } 54 | 55 | func reverse(s []int) { 56 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 57 | s[i], s[j] = s[j], s[i] 58 | } 59 | } 60 | 61 | func main() { 62 | 63 | nextPermutation([]int{1, 2, 3}) 64 | 65 | } 66 | -------------------------------------------------------------------------------- /nthUglyNumber.go: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ugly-number-ii/ 2 | // Author : 18plusui 3 | // Date : 2016-03-09 4 | 5 | /*************************************************************************************** 6 | * 7 | * Write a program to find the n-th ugly number. 8 | * 9 | * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For 10 | * example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 11 | * 12 | * Note that 1 is typically treated as an ugly number. 13 | * 14 | * The naive approach is to call isUgly for every number until you reach the nth one. 15 | * Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. 16 | * 17 | * An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. 18 | * 19 | * The key is how to maintain the order of the ugly numbers. Try a similar approach 20 | * of merging from three sorted lists: L1, L2, and L3. 21 | * 22 | * Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 23 | * * 5). 24 | * 25 | ***************************************************************************************/ 26 | 27 | package main 28 | 29 | import ( 30 | "fmt" 31 | ) 32 | 33 | func isNthUgly(n int) []int { 34 | 35 | var x, y, z int 36 | var res = make([]int, 0, 10) 37 | var culVal int 38 | //init slice res first value = 1 39 | res = append(res, 1) 40 | 41 | for len(res) < n { 42 | culVal = min(res[x]*2, res[y]*3, res[z]*5) 43 | fmt.Println("cul value : ", culVal) 44 | if culVal == res[x]*2 { 45 | x++ 46 | } 47 | if culVal == res[y]*3 { 48 | y++ 49 | } 50 | if culVal == res[z]*5 { 51 | z++ 52 | } 53 | res = append(res, culVal) 54 | } 55 | 56 | return res 57 | } 58 | 59 | func min(a, b, c int) int { 60 | return min2(min2(a, b), c) 61 | } 62 | 63 | func min2(a, b int) int { 64 | 65 | if a < b { 66 | return a 67 | } 68 | 69 | return b 70 | } 71 | 72 | func main() { 73 | 74 | fmt.Println(isNthUgly(10)) 75 | } 76 | -------------------------------------------------------------------------------- /regularExpressionMatching.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/regular-expression-matching/ 2 | // Author : 18plusui 3 | // Date : 2016-04-09 4 | 5 | /********************************************************************************** 6 | * 7 | * Implement regular expression matching with support for '.' and '*'. 8 | * 9 | * '.' Matches any single character. 10 | * '*' Matches zero or more of the preceding element. 11 | * 12 | * The matching should cover the entire input string (not partial). 13 | * 14 | * The function prototype should be: 15 | * bool isMatch(const char *s, const char *p) 16 | * 17 | * Some examples: 18 | * isMatch("aa","a") → false 19 | * isMatch("aa","aa") → true 20 | * isMatch("aaa","aa") → false 21 | * isMatch("aa", "a*") → true 22 | * isMatch("aa", ".*") → true 23 | * isMatch("ab", ".*") → true 24 | * isMatch("aab", "c*a*b") → true 25 | * 26 | **********************************************************************************/ 27 | 28 | package main 29 | 30 | import ( 31 | "fmt" 32 | ) 33 | 34 | func isMatch(s, p string) bool { 35 | 36 | if p == "" { 37 | return s == "" 38 | } 39 | 40 | if len(p) == 1 || (len(p) > 1 && string(p[1]) != "*") { 41 | if s == "" || (string(p[0]) != "." && string(s[0]) != string(p[0])) { 42 | return false 43 | } 44 | 45 | return isMatch(s[1:], p[1:]) 46 | 47 | } 48 | 49 | slen := len(s) 50 | i := -1 51 | 52 | for i < slen && (i < 0 || string(p[0]) == "." || p[0] == s[i]) { 53 | if len(p) >= 2 { 54 | if isMatch(s[i+1:], p[2:]) { 55 | return true 56 | } 57 | i++ 58 | }else{ 59 | if isMatch(s[i+1:], p[1:]) { 60 | return true 61 | } 62 | i++ 63 | } 64 | } 65 | 66 | return false 67 | 68 | } 69 | 70 | func main() { 71 | fmt.Println(isMatch("aa", ".")) 72 | fmt.Println(isMatch("aa", "*")) 73 | fmt.Println(isMatch("aaa", "aa")) 74 | fmt.Println(isMatch("aa", "a*")) 75 | fmt.Println(isMatch("aa", ".*")) 76 | fmt.Println(isMatch("ab", ".*")) 77 | fmt.Println(isMatch("aab", "c*a*b")) 78 | 79 | } 80 | -------------------------------------------------------------------------------- /removeDuplicatesFromSortedArray.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | // Author : 18plusui 3 | // Date : 2016-04-25 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a sorted array, remove the duplicates in place such that each element appear 8 | * only once and return the new length. 9 | * 10 | * Do not allocate extra space for another array, you must do this in place with constant memory. 11 | * 12 | * For example, 13 | * Given input array A = [1,1,2], 14 | * 15 | * Your function should return length = 2, and A is now [1,2]. 16 | * 17 | **********************************************************************************/ 18 | 19 | package main 20 | 21 | import ( 22 | "fmt" 23 | ) 24 | 25 | func removeDuplicates(input []int) int { 26 | 27 | length := len(input) 28 | 29 | if length <= 1 { 30 | return length 31 | } 32 | 33 | pos := 0 34 | 35 | for i := 0; i < length-1; i++ { 36 | 37 | if input[i] != input[i+1] { 38 | pos++ 39 | input[pos] = input[i+1] 40 | } 41 | 42 | } 43 | 44 | fmt.Println(input[:pos+1]) 45 | 46 | return pos + 1 47 | 48 | } 49 | 50 | func main() { 51 | input := []int{1, 1, 2, 3, 3, 3, 4, 5} 52 | length := removeDuplicates(input) 53 | fmt.Println(length) 54 | } 55 | -------------------------------------------------------------------------------- /removeNthNodeFromEndOfList.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/ 2 | // Author : 18plusui 3 | // Date : 2016-04-14 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a linked list, remove the nth node from the end of list and return its head. 8 | * 9 | * For example, 10 | * 11 | * Given linked list: 1->2->3->4->5, and n = 2. 12 | * 13 | * After removing the second node from the end, the linked list becomes 1->2->3->5. 14 | * 15 | * Note: 16 | * Given n will always be valid. 17 | * Try to do this in one pass. 18 | * 19 | **********************************************************************************/ 20 | 21 | package main 22 | 23 | import ( 24 | "fmt" 25 | ) 26 | 27 | type ListNode struct { 28 | Val int 29 | Next *ListNode 30 | } 31 | 32 | func removeNthFromEnd(head *ListNode, n int) *ListNode { 33 | 34 | if head == nil || n <= 0 { 35 | return nil 36 | } 37 | 38 | var fakeHead ListNode = ListNode{0,head} 39 | 40 | head = &fakeHead 41 | 42 | p1 := new(ListNode) 43 | p2 := new(ListNode) 44 | 45 | p1=head 46 | p2=head 47 | 48 | for i := 0; i < n; i++ { 49 | if p2 == nil { 50 | return nil 51 | } 52 | p2 = p2.Next 53 | } 54 | 55 | for p2.Next != nil{ 56 | p2 = p2.Next 57 | p1 = p1.Next 58 | } 59 | 60 | p1.Next = p1.Next.Next 61 | 62 | return head.Next 63 | } 64 | 65 | // func makeListNode(head *ListNode,num []int) *ListNode{ 66 | 67 | // numlen := len(num) 68 | 69 | // if numlen != 0 { 70 | // head.Val = num[0] 71 | // makeListNode(head.Next, num[1:]) 72 | // } 73 | 74 | // return head 75 | 76 | // } 77 | 78 | func main() { 79 | 80 | } 81 | -------------------------------------------------------------------------------- /reverseInt.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/reverse-integer/ 2 | // Author : 18plusui 3 | // Date : 2016-04-08 4 | 5 | /********************************************************************************** 6 | * 7 | * Reverse digits of an integer. 8 | * 9 | * Example1: x = 123, return 321 10 | * Example2: x = -123, return -321 11 | * 12 | * 13 | * Have you thought about this? 14 | * 15 | * Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 16 | * 17 | * > If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 18 | * 19 | * > Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, 20 | * then the reverse of 1000000003 overflows. How should you handle such cases? 21 | * 22 | * > Throw an exception? Good, but what if throwing an exception is not an option? 23 | * You would then have to re-design the function (ie, add an extra parameter). 24 | * 25 | * 26 | **********************************************************************************/ 27 | 28 | package main 29 | 30 | import ( 31 | "fmt" 32 | ) 33 | 34 | const ( 35 | INT_MAX int = 2147483647 36 | INT_MIN int = -2147483648 37 | ) 38 | 39 | func reverse(x int) int { 40 | y := 0 41 | var n int 42 | for x != 0 { 43 | n = x % 10 44 | if y > INT_MAX/10 || y < INT_MIN/10 { 45 | return 0 46 | } 47 | y = y*10 + n 48 | x /= 10 49 | } 50 | fmt.Println(y) 51 | return y 52 | } 53 | 54 | func main() { 55 | reverse(123155123) 56 | } 57 | -------------------------------------------------------------------------------- /reverseNodesInKGroup.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/reverse-nodes-in-k-group/ 2 | // Author : 18plusui 3 | // Date : 2016-04-24 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 8 | * 9 | * If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. 10 | * 11 | * You may not alter the values in the nodes, only nodes itself may be changed. 12 | * 13 | * Only constant memory is allowed. 14 | * 15 | * For example, 16 | * Given this linked list: 1->2->3->4->5 17 | * 18 | * For k = 2, you should return: 2->1->4->3->5 19 | * 20 | * For k = 3, you should return: 3->2->1->4->5 21 | * 22 | **********************************************************************************/ 23 | // Source : https://oj.leetcode.com/problems/swap-nodes-in-pairs/ 24 | // Author : 18plusui 25 | // Date : 2016-04-24 26 | 27 | /********************************************************************************** 28 | * 29 | * Given a linked list, swap every two adjacent nodes and return its head. 30 | * 31 | * For example, 32 | * Given 1->2->3->4, you should return the list as 2->1->4->3. 33 | * 34 | * Your algorithm should use only constant space. You may not modify the values in the list, 35 | * only nodes itself can be changed. 36 | * 37 | **********************************************************************************/ 38 | 39 | package main 40 | 41 | import ( 42 | "fmt" 43 | ) 44 | 45 | type ListNode struct { 46 | Val int 47 | Next *ListNode 48 | } 49 | 50 | func (l *ListNode) setVal(val int) *ListNode { 51 | l.Val = val 52 | l.Next = nil 53 | return l 54 | } 55 | 56 | func reverseKGroup(head *ListNode, k int) *ListNode { 57 | lists := getListSlice(head) 58 | 59 | if len(lists) < k { 60 | return head 61 | } 62 | 63 | for n := 1; n <= len(lists)/k; n++ { 64 | 65 | for i := 0; i+(n-1)*k != n*k-i-1; i++ { 66 | 67 | lists[i+(n-1)*k].Val, lists[n*k-i-1].Val = lists[n*k-i-1].Val, lists[i+(n-1)*k].Val 68 | 69 | } 70 | } 71 | 72 | return head 73 | } 74 | 75 | func createList(intSlice []int, ln *ListNode) *ListNode { 76 | n := len(intSlice) 77 | head := new(ListNode) 78 | 79 | if n != 0 { 80 | val := intSlice[n-1] 81 | ln.Next = head.setVal(val) 82 | } else { 83 | return ln 84 | } 85 | 86 | n-- 87 | 88 | createList(intSlice[:n], ln.Next) 89 | return ln.Next 90 | } 91 | 92 | func getListSlice(list *ListNode) []*ListNode { 93 | 94 | var ListSlice []*ListNode 95 | 96 | for list != nil { 97 | ListSlice = append(ListSlice, list) 98 | list = list.Next 99 | 100 | } 101 | 102 | return ListSlice 103 | } 104 | 105 | func printList(list *ListNode) { 106 | for list != nil { 107 | fmt.Println(list.Val) 108 | list = list.Next 109 | 110 | } 111 | } 112 | 113 | func main() { 114 | a := []int{4, 4, 3, 2, 1, 7, 8, 5, 6, 1, 2} 115 | 116 | la := new(ListNode) 117 | la = createList(a, la) 118 | // printList(la) 119 | 120 | ln := reverseKGroup(la, 5) 121 | printList(ln) 122 | } 123 | -------------------------------------------------------------------------------- /romanToInteger.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/roman-to-integer/ 2 | // Author : 18plusui 3 | // Date : 2016-04-12 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a roman numeral, convert it to an integer. 8 | * 9 | * Input is guaranteed to be within the range from 1 to 3999. 10 | * 11 | **********************************************************************************/ 12 | 13 | package main 14 | 15 | import ( 16 | "fmt" 17 | ) 18 | 19 | func romanToIntHelper(str string) int{ 20 | var d int 21 | switch(str){ 22 | 23 | case "I" : 24 | d = 1 25 | break 26 | case "V" : 27 | d = 5 28 | break 29 | case "X" : 30 | d = 10 31 | break 32 | case "L" : 33 | d = 50 34 | break 35 | case "C" : 36 | d = 100 37 | break 38 | case "D" : 39 | d = 500 40 | break 41 | case "M" : 42 | d = 100 43 | break 44 | } 45 | 46 | return d 47 | } 48 | 49 | func romanToInt (s string) int { 50 | 51 | if len(s) <= 0 {return 0} 52 | 53 | result := romanToIntHelper(s) 54 | for i := 1; i < len(s); i++ { 55 | prev := romanToIntHelper(string(s[i-1])) 56 | curr := romanToIntHelper(string(s[i])) 57 | 58 | if prev < curr { 59 | result = result - prev + (curr - prev) 60 | } else { 61 | result += curr 62 | } 63 | } 64 | 65 | return result 66 | 67 | } 68 | 69 | func main() { 70 | fmt.Println(romanToInt("XL")) 71 | } 72 | -------------------------------------------------------------------------------- /searchForRange.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/search-for-a-range/ 2 | // Author : 18plusui 3 | // Date : 2016-04-28 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a sorted array of integers, find the starting and ending position of a given target value. 8 | * 9 | * Your algorithm's runtime complexity must be in the order of O(log n). 10 | * 11 | * If the target is not found in the array, return [-1, -1]. 12 | * 13 | * For example, 14 | * Given [5, 7, 7, 8, 8, 10] and target value 8, 15 | * return [3, 4]. 16 | * 17 | **********************************************************************************/ 18 | 19 | package main 20 | 21 | import ( 22 | "fmt" 23 | ) 24 | 25 | func searchRange(nums []int, target int) []int { 26 | n := len(nums) 27 | pos := binarySearch(nums, 0, n-1, target) 28 | 29 | var result []int 30 | low, high := -1, -1 31 | if pos >= 0 { 32 | high = pos 33 | low = high 34 | 35 | l := binarySearch(nums, 0, low-1, target) 36 | for l >= 0 { 37 | low = l 38 | l = binarySearch(nums, 0, low-1, target) 39 | } 40 | 41 | h := binarySearch(nums, high+1, n-1, target) 42 | for h >= 0 { 43 | high = h 44 | h = binarySearch(nums, high+1, n-1, target) 45 | } 46 | } 47 | result = append(result, low) 48 | result = append(result, high) 49 | 50 | return result 51 | } 52 | 53 | func binarySearch(nums []int, low, high, target int) int { 54 | for low <= high { 55 | mid := low + (high-low)/2 56 | if nums[mid] == target { 57 | return mid 58 | } 59 | 60 | if target > nums[mid] { 61 | low = mid + 1 62 | } 63 | 64 | if target < nums[mid] { 65 | high = mid - 1 66 | } 67 | } 68 | return -1 69 | 70 | } 71 | 72 | func main() { 73 | fmt.Println(searchRange([]int{1, 2, 2}, 2)) 74 | } 75 | -------------------------------------------------------------------------------- /searchInRotatedSortedArray.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/search-in-rotated-sorted-array/ 2 | // Author : 18plusui 3 | // Date : 2016-04-28 4 | 5 | /********************************************************************************** 6 | * 7 | * Suppose a sorted array is rotated at some pivot unknown to you beforehand. 8 | * 9 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | * 11 | * You are given a target value to search. If found in the array return its index, otherwise return -1. 12 | * 13 | * You may assume no duplicate exists in the array. 14 | * 15 | **********************************************************************************/ 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | ) 22 | 23 | func search(A []int, key int) int { 24 | n := len(A) 25 | if n <= 0 { 26 | return -1 27 | } 28 | 29 | if n == 1 { 30 | if A[0] == key { 31 | return 0 32 | } 33 | return -1 34 | } 35 | 36 | low, high := 0, n-1 37 | 38 | for low <= high { 39 | if A[low] <= A[high] && (key < A[low] || key > A[high]) { 40 | return -1 41 | } 42 | 43 | mid := low + (high-low)/2 44 | 45 | if A[mid] == key { 46 | return mid 47 | } 48 | 49 | if A[low] < A[mid] && key >= A[low] && key < A[mid] { 50 | high = mid - 1 51 | continue 52 | } 53 | 54 | if A[mid] < A[high] && key > A[mid] && key <= A[high] { 55 | low = mid + 1 56 | continue 57 | } 58 | 59 | if A[low] > A[mid] { 60 | high = mid - 1 61 | continue 62 | } 63 | 64 | if A[mid] > A[high] { 65 | low = mid + 1 66 | continue 67 | } 68 | } 69 | 70 | return -1 71 | 72 | } 73 | 74 | func main() { 75 | fmt.Println(search([]int{1, 3}, 2)) 76 | } 77 | -------------------------------------------------------------------------------- /searchInsert.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/search-insert-position/ 2 | // Author : 18plusui 3 | // Date : 2016-04-28 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a sorted array and a target value, return the index if the target is found. 8 | * If not, return the index where it would be if it were inserted in order. 9 | * 10 | * You may assume no duplicates in the array. 11 | * 12 | * Here are few examples. 13 | * [1,3,5,6], 5 → 2 14 | * [1,3,5,6], 2 → 1 15 | * [1,3,5,6], 7 → 4 16 | * [1,3,5,6], 0 → 0 17 | * 18 | **********************************************************************************/ 19 | 20 | package main 21 | 22 | import ( 23 | "fmt" 24 | ) 25 | 26 | func binarySearch(nums []int, target int) int { 27 | n := len(nums) 28 | low := 0 29 | high := n - 1 30 | 31 | for low <= high { 32 | mid := low + (high-low)/2 33 | if nums[mid] == target { 34 | return mid 35 | } 36 | if target > nums[mid] { 37 | low = mid + 1 38 | } else { 39 | high = mid - 1 40 | } 41 | 42 | } 43 | 44 | return low 45 | } 46 | 47 | func searchInsert(nums []int, target int) int { 48 | if len(nums) == 0 { 49 | return len(nums) 50 | } 51 | return binarySearch(nums, target) 52 | } 53 | 54 | func main() { 55 | fmt.Println(searchInsert([]int{1, 2, 3, 4, 5}, 2)) 56 | } 57 | -------------------------------------------------------------------------------- /skylineProblem.go: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/the-skyline-problem/ 2 | // Author : 18plusui 3 | // Date : 2016-03-13 4 | 5 | /********************************************************************************** 6 | * 7 | * A city's skyline is the outer contour of the silhouette formed by all the buildings 8 | * in that city when viewed from a distance. Now suppose you are given the locations and 9 | * height of all the buildings as shown on a cityscape photo (Figure A), write a program 10 | * to output the skyline formed by these buildings collectively (Figure B). 11 | * 12 | * ^ ^ 13 | * | | 14 | * | | 15 | * | +-----+ | O-----+ 16 | * | | | | | | 17 | * | | | | | | 18 | * | | +--+------+ | | O------+ 19 | * | | | | | | | 20 | * | +-+--+----+ | +------+ | O-+ | O------+ 21 | * | | | | | | | | | | | 22 | * | | | | | +-+--+ | | | | O--+ 23 | * | | | | | | | | | | | | 24 | * | | | | | | | | | | | | 25 | * | | | | | | | | | | | | 26 | * | | | | | | | | | | | | 27 | * +--+---------+----+---+----+----+---> +--+--------------O---+---------O---> 28 | * 29 | * https://leetcode.com/static/images/problemset/skyline1.jpg 30 | * https://leetcode.com/static/images/problemset/skyline2.jpg 31 | * 32 | * The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], 33 | * where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, 34 | * and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 , and Ri - Li > 0. 35 | * You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. 36 | * 37 | * For instance, the dimensions of all buildings in Figure A are recorded as: 38 | * [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] . 39 | * 40 | * The output is a list of "key points" (red dots in Figure B) in the format of 41 | * [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. 42 | * A key point is the left endpoint of a horizontal line segment. 43 | * 44 | * Note that the last key point, where the rightmost building ends, is merely used to mark 45 | * the termination of the skyline, and always has zero height. Also, the ground in between 46 | * any two adjacent buildings should be considered part of the skyline contour. 47 | * 48 | * For instance, the skyline in Figure B should be represented as: 49 | * [ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ]. 50 | * 51 | * Notes: 52 | * 53 | * - The number of buildings in any input list is guaranteed to be in the range [0, 10000]. 54 | * - The input list is already sorted in ascending order by the left x position Li. 55 | * - The output list must be sorted by the x position. 56 | * - There must be no consecutive horizontal lines of equal height in the output skyline. 57 | * For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; 58 | * the three lines of height 5 should be merged into one in the final output as such: 59 | * [...[2 3], [4 5], [12 7], ...] 60 | * 61 | * Credits: Special thanks to @stellari for adding this problem, 62 | * creating these two awesome images and all test cases. 63 | * 64 | **********************************************************************************/ 65 | package main 66 | 67 | import ( 68 | "fmt" 69 | "sort" 70 | ) 71 | 72 | type point struct { 73 | x int 74 | y int 75 | } 76 | 77 | type arrPoint []point 78 | 79 | func (s arrPoint) Len() int { return len(s) } 80 | func (s arrPoint) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 81 | 82 | type ByX struct{ arrPoint } 83 | 84 | func (s ByX) Less(i, j int) bool { 85 | 86 | if s.arrPoint[i].x == s.arrPoint[j].x && s.arrPoint[i].y <= s.arrPoint[j].y { 87 | return true 88 | } 89 | return s.arrPoint[i].x < s.arrPoint[j].x 90 | } 91 | 92 | func getSkyline(input [][]int) []point { 93 | var edges []point 94 | 95 | var left, right, height int 96 | for i := 0; i < len(input); i++ { 97 | left = input[i][0] 98 | right = input[i][1] 99 | height = input[i][2] 100 | 101 | edges = append(edges, point{left, -height}) 102 | edges = append(edges, point{right, height}) 103 | 104 | } 105 | 106 | sort.Sort(ByX{edges}) 107 | 108 | fmt.Println(edges) 109 | var res []point 110 | 111 | var pre, curr int 112 | var m []int 113 | var mLen int 114 | m = append(m, 0) 115 | 116 | for i := 0; i < len(edges); i++ { 117 | e := edges[i] 118 | 119 | if e.y < 0 { 120 | if pre > -e.y { 121 | m = append(m, -e.y) 122 | continue 123 | } 124 | m = append(m, -e.y) 125 | 126 | } else { 127 | for j, v := range m { 128 | if v == e.y { 129 | 130 | m = append(m[:j], m[j+1:]...) 131 | 132 | } 133 | 134 | } 135 | 136 | } 137 | mLen = len(m) 138 | 139 | curr = m[mLen-1] 140 | 141 | if curr != pre { 142 | res = append(res, point{e.x, curr}) 143 | pre = curr 144 | } 145 | 146 | } 147 | 148 | return res 149 | } 150 | func reverse(s []int) { 151 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 152 | s[i], s[j] = s[j], s[i] 153 | } 154 | } 155 | func main() { 156 | 157 | res := [][]int{{2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8}} 158 | 159 | fmt.Println(res) 160 | // getSkyline(res) 161 | fmt.Println(getSkyline(res)) 162 | } 163 | -------------------------------------------------------------------------------- /strStr.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/implement-strstr/ 2 | // Author : 18plusui 3 | // Date : 2016-04-25 4 | 5 | /********************************************************************************** 6 | * 7 | * Implement strStr(). 8 | * 9 | * Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 10 | * 11 | **********************************************************************************/ 12 | 13 | package main 14 | 15 | import ( 16 | "fmt" 17 | ) 18 | 19 | func strStr(haystack, needle string) int { 20 | if len(haystack) < len(needle) { 21 | return -1 22 | } 23 | index, i, j := 0, 0, 0 24 | for i < len(haystack) && j < len(needle) { 25 | if haystack[i] == needle[j] { 26 | i++ 27 | j++ 28 | } else { 29 | index++ 30 | i = index 31 | j = 0 32 | } 33 | } 34 | 35 | if j == len(needle) { 36 | return index 37 | } 38 | return -1 39 | } 40 | 41 | func main() { 42 | fmt.Println(strStr("abcd", "a")) 43 | } 44 | -------------------------------------------------------------------------------- /stringToIntegerAtoi.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/string-to-integer-atoi/ 2 | // Author : 18plusui 3 | // Date : 2016-04-09 4 | 5 | /********************************************************************************** 6 | * 7 | * Implement atoi to convert a string to an integer. 8 | * 9 | * Hint: Carefully consider all possible input cases. If you want a challenge, 10 | * please do not see below and ask yourself what are the possible input cases. 11 | * 12 | * Notes: 13 | * It is intended for this problem to be specified vaguely (ie, no given input specs). 14 | * You are responsible to gather all the input requirements up front. 15 | * 16 | * 17 | * Requirements for atoi: 18 | * 19 | * The function first discards as many whitespace characters as necessary until the first 20 | * non-whitespace character is found. Then, starting from this character, takes an optional 21 | * initial plus or minus sign followed by as many numerical digits as possible, and interprets 22 | * them as a numerical value. 23 | * 24 | * The string can contain additional characters after those that form the integral number, 25 | * which are ignored and have no effect on the behavior of this function. 26 | * 27 | * If the first sequence of non-whitespace characters in str is not a valid integral number, 28 | * or if no such sequence exists because either str is empty or it contains only whitespace 29 | * characters, no conversion is performed. 30 | * 31 | * If no valid conversion could be performed, a zero value is returned. If the correct value 32 | * is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) 33 | * is returned. 34 | * 35 | **********************************************************************************/ 36 | 37 | package main 38 | 39 | import ( 40 | "fmt" 41 | "strconv" 42 | ) 43 | 44 | // learn more detail from https://golang.org/src/strconv/atoi.go?h=strconv 45 | 46 | func main() { 47 | hello, world := strconv.Atoi("-123451") 48 | if world != nil { 49 | fmt.Errorf("hello world err : ", world) 50 | } 51 | fmt.Println(hello) 52 | } 53 | -------------------------------------------------------------------------------- /substringWithConcatenationOfAllWords.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/ 2 | // Author : 18plusui 3 | // Date : 2016-04-27 4 | 5 | /********************************************************************************** 6 | * 7 | * You are given a string, S, and a list of words, L, that are all of the same length. 8 | * Find all starting indices of substring(s) in S that is a concatenation of each word 9 | * in L exactly once and without any intervening characters. 10 | * 11 | * For example, given: 12 | * S: "barfoothefoobarman" 13 | * L: ["foo", "bar"] 14 | * 15 | * You should return the indices: [0,9]. 16 | * (order does not matter). 17 | * 18 | **********************************************************************************/ 19 | 20 | package main 21 | 22 | import ( 23 | "fmt" 24 | ) 25 | 26 | func findSubstr(S string, L []string) []int { 27 | var result []int 28 | 29 | if len(S) <= 0 || len(L) <= 0 { 30 | return result 31 | } 32 | 33 | n, m, l := len(S), len(L), len(L[0]) 34 | 35 | expected := make(map[string]int) 36 | for i := 0; i < m; i++ { 37 | _, ok := expected[L[i]] 38 | if ok { 39 | expected[L[i]]++ 40 | } else { 41 | expected[L[i]] = 1 42 | } 43 | } 44 | 45 | for i := 0; i < l; i++ { 46 | actual := make(map[string]int) 47 | count, winleft := 0, i 48 | 49 | for j := i; j <= n-l; j += l { 50 | 51 | word := S[j : j+l] 52 | _, ok := expected[word] 53 | if !ok { 54 | for k := range actual { 55 | delete(actual, k) 56 | } 57 | count = 0 58 | winleft = j + l 59 | continue 60 | } 61 | count++ 62 | 63 | _, ok = actual[word] 64 | if !ok { 65 | actual[word] = 1 66 | } else { 67 | actual[word]++ 68 | } 69 | 70 | if actual[word] > expected[word] { 71 | 72 | tmp := S[winleft : winleft+l] 73 | count-- 74 | actual[tmp]-- 75 | winleft += l 76 | for tmp != word { 77 | tmp = S[winleft : winleft+l] 78 | count-- 79 | actual[tmp]-- 80 | winleft += l 81 | } 82 | 83 | } 84 | 85 | if count == m { 86 | result = append(result, winleft) 87 | tmp := S[winleft : winleft+l] 88 | actual[tmp]-- 89 | winleft += l 90 | count-- 91 | } 92 | 93 | } 94 | } 95 | 96 | return result 97 | 98 | } 99 | 100 | func main() { 101 | 102 | fmt.Println(findSubstr("barfoothefoobarman", []string{"foo", "bar"})) 103 | 104 | } 105 | -------------------------------------------------------------------------------- /swapNodesInPairs.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/swap-nodes-in-pairs/ 2 | // Author : 18plusui 3 | // Date : 2016-04-24 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a linked list, swap every two adjacent nodes and return its head. 8 | * 9 | * For example, 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 in the list, 13 | * only nodes itself can be changed. 14 | * 15 | **********************************************************************************/ 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | ) 22 | 23 | type ListNode struct { 24 | Val int 25 | Next *ListNode 26 | } 27 | 28 | func (l *ListNode) setVal(val int) *ListNode { 29 | l.Val = val 30 | l.Next = nil 31 | return l 32 | } 33 | 34 | func swapPairs(head *ListNode) *ListNode { 35 | for p := head; p != nil && p.Next != nil; p = p.Next.Next { 36 | p.Val, p.Next.Val = p.Next.Val, p.Val 37 | } 38 | return head 39 | } 40 | 41 | func createList(intSlice []int, ln *ListNode) *ListNode { 42 | n := len(intSlice) 43 | head := new(ListNode) 44 | 45 | if n != 0 { 46 | val := intSlice[n-1] 47 | ln.Next = head.setVal(val) 48 | } else { 49 | return ln 50 | } 51 | 52 | n-- 53 | 54 | createList(intSlice[:n], ln.Next) 55 | return ln.Next 56 | } 57 | 58 | func printList(list *ListNode) { 59 | for list != nil { 60 | fmt.Println("===", list.Val) 61 | list = list.Next 62 | 63 | } 64 | } 65 | 66 | func main() { 67 | a := []int{4, 4, 3, 2, 1} 68 | 69 | la := new(ListNode) 70 | la = createList(a, la) 71 | ln := swapPairs(la) 72 | printList(ln) 73 | } 74 | -------------------------------------------------------------------------------- /symmetricTree.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/symmetric-tree/ 2 | // Author : 18plusui 3 | // Date : 2016-03-15 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 8 | * 9 | * For example, this binary tree is symmetric: 10 | * 11 | * 1 12 | * / \ 13 | * 2 2 14 | * / \ / \ 15 | * 3 4 4 3 16 | * 17 | * But the following is not: 18 | * 19 | * 1 20 | * / \ 21 | * 2 2 22 | * \ \ 23 | * 3 3 24 | * 25 | * Note: 26 | * Bonus points if you could solve it both recursively and iteratively. 27 | * 28 | * confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 29 | * 30 | * OJ's Binary Tree Serialization: 31 | * 32 | * The serialization of a binary tree follows a level order traversal, where '#' signifies 33 | * a path terminator where no node exists below. 34 | * 35 | * Here's an example: 36 | * 37 | * 1 38 | * / \ 39 | * 2 3 40 | * / 41 | * 4 42 | * \ 43 | * 5 44 | * 45 | * The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 46 | * 47 | **********************************************************************************/ 48 | 49 | package main 50 | 51 | import ( 52 | "fmt" 53 | ) 54 | 55 | type Tree struct { 56 | Left *Tree 57 | Value int 58 | Right *Tree 59 | } 60 | 61 | func CreateSymmetricTree(inputArr []int) *Tree { 62 | var t *Tree 63 | var count int 64 | for _, v := range inputArr { 65 | 66 | t = insertLeft(t, v, count) 67 | } 68 | 69 | count = 0 70 | for _, v := range inputArr { 71 | 72 | if v == t.Value { 73 | continue 74 | } 75 | 76 | t = insertRight(t, v, count) 77 | } 78 | return t 79 | } 80 | 81 | func insertLeft(t *Tree, v, count int) *Tree { 82 | count++ 83 | if t == nil { 84 | return &Tree{nil, v, nil} 85 | } 86 | 87 | if t.Left == nil { 88 | 89 | t.Left = insertLeft(t.Left, v, count) 90 | return t 91 | } 92 | 93 | if t.Left == nil || count == 1 { 94 | 95 | t.Left = insertLeft(t.Left, v, count) 96 | return t 97 | } 98 | 99 | t.Right = insertLeft(t.Right, v, count) 100 | 101 | return t 102 | } 103 | 104 | func insertRight(t *Tree, v, count int) *Tree { 105 | count++ 106 | if t == nil { 107 | return &Tree{nil, v, nil} 108 | } 109 | 110 | if t.Right == nil { 111 | 112 | t.Right = insertRight(t.Right, v, count) 113 | return t 114 | } 115 | 116 | if t.Right == nil || count == 1 { 117 | 118 | t.Right = insertRight(t.Right, v, count) 119 | return t 120 | } 121 | 122 | t.Left = insertRight(t.Left, v, count) 123 | 124 | return t 125 | } 126 | 127 | // above code is generate Symmetric Tree 128 | 129 | func isSymmetric(t *Tree) bool { 130 | if t == nil { 131 | return true 132 | } 133 | 134 | return isSymmetricNode(t.Left, t.Right) 135 | } 136 | 137 | func isSymmetricNode(left, right *Tree) bool { 138 | if left == nil && right == nil { 139 | return true 140 | } 141 | 142 | if left == nil || right == nil { 143 | return false 144 | } 145 | 146 | return (left.Value == right.Value) && isSymmetricNode(left.Left, right.Right) && isSymmetricNode(left.Right, right.Left) 147 | } 148 | 149 | func printer(t *Tree) { 150 | if t == nil { 151 | fmt.Println("#") 152 | return 153 | 154 | } 155 | fmt.Println(t.Value) 156 | printer(t.Left) 157 | printer(t.Right) 158 | 159 | } 160 | 161 | func main() { 162 | 163 | inputArr := []int{6, 5, 4, 3, 2, 1} 164 | t := CreateSymmetricTree(inputArr) 165 | 166 | printer(t) 167 | fmt.Println(isSymmetric(t)) 168 | 169 | } 170 | -------------------------------------------------------------------------------- /testJustification.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/text-justification/ 2 | // Author : 18plusui 3 | // Date : 2016-03-14 4 | 5 | /********************************************************************************** 6 | * 7 | * Given an array of words and a length L, format the text such that each line has 8 | * exactly L characters and is fully (left and right) justified. 9 | * 10 | * 11 | * You should pack your words in a greedy approach; that is, pack as many words as you can in each line. 12 | * Pad extra spaces ' ' when necessary so that each line has exactly L characters. 13 | * 14 | * Extra spaces between words should be distributed as evenly as possible. 15 | * If the number of spaces on a line do not divide evenly between words, 16 | * the empty slots on the left will be assigned more spaces than the slots on the right. 17 | * 18 | * For the last line of text, it should be left justified and no extra space is inserted between words. 19 | * 20 | * For example, 21 | * words: ["This", "is", "an", "example", "of", "text", "justification."] 22 | * L: 16. 23 | * 24 | * Return the formatted lines as: 25 | * 26 | * [ 27 | * "This is an", 28 | * "example of text", 29 | * "justification. " 30 | * ] 31 | * 32 | * Note: Each word is guaranteed not to exceed L in length. 33 | * 34 | * 35 | * Corner Cases: 36 | * 37 | * A line other than the last line might contain only one word. What should you do in this case? 38 | * In this case, that line should be left-justified. 39 | * 40 | **********************************************************************************/ 41 | 42 | package main 43 | 44 | import ( 45 | "fmt" 46 | ) 47 | 48 | func fullJustify(input []string, long int) []string { 49 | var slen, start, end, space int 50 | var lastLine bool 51 | var result []string 52 | for i := 0; i < len(input); i++ { 53 | 54 | slen += len(input[i]) 55 | 56 | if slen+i-start > long || i == len(input)-1 { 57 | 58 | if slen+i-start > long { 59 | 60 | slen -= len(input[i]) 61 | end = i - 1 62 | lastLine = false 63 | } else { 64 | end = i 65 | lastLine = true 66 | } 67 | 68 | space = long - slen 69 | 70 | var mspace int 71 | var extra int 72 | if lastLine { 73 | mspace = 1 74 | extra = 0 75 | } else { 76 | mspace = space / (end - start) 77 | extra = space - mspace*(end-start) 78 | } 79 | 80 | var line string = input[start] 81 | 82 | for j := start + 1; j <= i-1; j++ { 83 | for k := 0; k < mspace && space > 0; k++ { 84 | line += " " 85 | space-- 86 | } 87 | if j-start-1 < extra { 88 | line += " " 89 | space-- 90 | } 91 | line += input[j] 92 | } 93 | 94 | if space > 0 { 95 | for ; space > 0; space-- { 96 | line += " " 97 | } 98 | } 99 | result = append(result, line) 100 | start = i 101 | i = end 102 | slen = 0 103 | } 104 | 105 | } 106 | 107 | return result 108 | 109 | } 110 | 111 | func main() { 112 | test := []string{"This", "is", "an", "example", "of", "text", "justification."} 113 | res := fullJustify(test, 16) 114 | for _, v := range res { 115 | fmt.Println(v) 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /trappingRainWater.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/trapping-rain-water/ 2 | // Author : 18plusui 3 | // Date : 2016-03-12 4 | 5 | /********************************************************************************** 6 | * 7 | * Given n non-negative integers representing an elevation map where the width of each bar is 1, 8 | * compute how much water it is able to trap after raining. 9 | * 10 | * For example, 11 | * Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 12 | * 13 | * ^ 14 | * | 15 | * 3 | +--+ 16 | * | | | 17 | * 2 | +--+xxxxxxxxx| +--+xx+--+ 18 | * | | |xxxxxxxxx| | |xx| | 19 | * 1 | +--+xxx| +--+xxx+--+ | +--+ +--+ 20 | * | | |xxx| | |xxx| | | | | | | 21 | * 0 +---+--+---+--+--+---+--+--+--+--+--+--+-----> 22 | * 0 1 0 2 1 0 1 3 2 1 2 1 23 | * 24 | * The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 25 | * 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! 26 | * 27 | **********************************************************************************/ 28 | 29 | package main 30 | 31 | import ( 32 | "fmt" 33 | ) 34 | 35 | func trappingRain(input []int) int { 36 | var res, maxHigh, maxIdx, preHigh int 37 | 38 | for i, v := range input { 39 | if v > maxHigh { 40 | maxHigh = v 41 | maxIdx = i 42 | } 43 | } 44 | 45 | for i := 0; i < maxIdx; i++ { 46 | if input[i] > preHigh { 47 | preHigh = input[i] 48 | } 49 | res += preHigh - input[i] 50 | } 51 | 52 | preHigh = 0 53 | for i := len(input) - 1; i > maxIdx; i-- { 54 | if input[i] > preHigh { 55 | preHigh = input[i] 56 | } 57 | res += preHigh - input[i] 58 | } 59 | return res 60 | } 61 | 62 | func main() { 63 | 64 | input := []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1} 65 | fmt.Println(trappingRain(input)) 66 | } 67 | -------------------------------------------------------------------------------- /triangle.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/triangle/ 2 | // Author : 18plusui 3 | // Date : 2016-03-11 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a triangle, find the minimum path sum from top to bottom. 8 | * Each step you may move to adjacent numbers on the row below. 9 | * 10 | * For example, given the following triangle 11 | * 12 | * [ 13 | * [2], 14 | * [3,4], 15 | * [6,5,7], 16 | * [4,1,8,3] 17 | * ] 18 | * 19 | * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 20 | * 21 | * Note: 22 | * Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 23 | * 24 | **********************************************************************************/ 25 | 26 | package main 27 | 28 | import ( 29 | "fmt" 30 | "math/rand" 31 | "sort" 32 | "time" 33 | ) 34 | 35 | func minTotal(inputTri [][]int) int { 36 | var minT int 37 | for i := 0; i < len(inputTri); i++ { 38 | if i == 0 { 39 | minT += inputTri[0][0] 40 | continue 41 | } 42 | 43 | intSort := inputTri[i] 44 | sort.Ints(intSort) 45 | minT += intSort[0] 46 | 47 | } 48 | return minT 49 | } 50 | 51 | func createTriangle(size int) [][]int { 52 | var row int 53 | 54 | for i := 1; i <= size; i++ { 55 | 56 | if (i*(i+1))/2 == size { 57 | row = i 58 | break 59 | } 60 | 61 | } 62 | 63 | res := make([][]int, row) 64 | for i := 0; i < row; i++ { 65 | innerLen := i + 1 66 | res[i] = make([]int, innerLen) 67 | for j := 0; j < innerLen; j++ { 68 | s1 := rand.NewSource(time.Now().UnixNano()) 69 | r1 := rand.New(s1) 70 | res[i][j] = r1.Intn(30) 71 | time.Sleep(1) 72 | } 73 | } 74 | 75 | fmt.Println(res) 76 | return res 77 | } 78 | 79 | func main() { 80 | inputTri := createTriangle(10) 81 | fmt.Println(minTotal(inputTri)) 82 | } 83 | -------------------------------------------------------------------------------- /uglyNumber.go: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/ugly-number/ 2 | // Author : 18plusui 3 | // Date : 2016-03-09 4 | 5 | /*************************************************************************************** 6 | * 7 | * Write a program to check whether a given number is an ugly number. 8 | * 9 | * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For 10 | * example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 11 | * 12 | * Note that 1 is typically treated as an ugly number. 13 | * 14 | ***************************************************************************************/ 15 | 16 | package main 17 | 18 | import ( 19 | "fmt" 20 | ) 21 | 22 | func isUgly(num int) bool { 23 | if num == 0 { 24 | return false 25 | } 26 | 27 | if num == 1 { 28 | return true 29 | } 30 | 31 | for num%2 == 0 { 32 | num /= 2 33 | fmt.Println("number 2: ", num) 34 | } 35 | 36 | for num%3 == 0 { 37 | num /= 3 38 | fmt.Println("number 3: ", num) 39 | } 40 | 41 | for num%5 == 0 { 42 | num /= 5 43 | fmt.Println("number 5: ", num) 44 | } 45 | 46 | return num == 1 47 | 48 | } 49 | 50 | func main() { 51 | fmt.Println(isUgly(100)) 52 | } 53 | -------------------------------------------------------------------------------- /uniqueBSTII.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ 2 | // Author : 18plusui 3 | // Date : 2016-03-08 4 | 5 | /********************************************************************************** 6 | * 7 | * Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. 8 | * 9 | * For example, 10 | * Given n = 3, your program should return all 5 unique BST's shown below. 11 | * 12 | * 1 3 3 2 1 13 | * \ / / / \ \ 14 | * 3 2 1 1 3 2 15 | * 16 | * confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 17 | **********************************************************************************/ 18 | package main 19 | 20 | import ( 21 | "fmt" 22 | ) 23 | 24 | type Tree struct { 25 | Left *Tree 26 | Value int 27 | Right *Tree 28 | } 29 | 30 | func (t *Tree) newTree(n int) *Tree { 31 | t.Value = n 32 | t.Left = nil 33 | t.Right = nil 34 | return t 35 | } 36 | 37 | func generateTreeI(n int) []*Tree { 38 | var resArr []*Tree 39 | resArr = generateTree(1, n) 40 | return resArr 41 | } 42 | 43 | func generateTree(low, high int) []*Tree { 44 | var res []*Tree 45 | 46 | if low > high || low <= 0 || high <= 0 { 47 | res = append(res, nil) 48 | return res 49 | } 50 | 51 | if low == high { 52 | tree := new(Tree) 53 | res = append(res, tree.newTree(low)) 54 | return res 55 | } 56 | 57 | for i := low; i <= high; i++ { 58 | var arrL []*Tree = generateTree(low, i-1) 59 | var arrR []*Tree = generateTree(i+1, high) 60 | for l := 0; l < len(arrL); l++ { 61 | for r := 0; r < len(arrR); r++ { 62 | root := new(Tree) 63 | root.newTree(i) 64 | root.Left = arrL[l] 65 | root.Right = arrR[r] 66 | res = append(res, root) 67 | } 68 | } 69 | 70 | } 71 | return res 72 | } 73 | 74 | func printer(t *Tree) { 75 | if t == nil { 76 | fmt.Println("#") 77 | return 78 | 79 | } 80 | fmt.Println(t.Value) 81 | printer(t.Left) 82 | printer(t.Right) 83 | 84 | } 85 | 86 | func main() { 87 | t := new(Tree) 88 | fmt.Println(t.newTree(0)) 89 | var res []*Tree = generateTreeI(3) 90 | for i, v := range res { 91 | fmt.Println("the loop number : ", i) 92 | printer(v) 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /uniquePath.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/unique-paths/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 8 | * 9 | * The robot can only move either down or right at any point in time. The robot is trying to reach 10 | * the bottom-right corner of the grid (marked 'Finish' in the diagram below). 11 | * 12 | * 13 | * start 14 | * +---------+----+----+----+----+----+ 15 | * |----| | | | | | | 16 | * |----| | | | | | | 17 | * +----------------------------------+ 18 | * | | | | | | | | 19 | * | | | | | | | | 20 | * +----------------------------------+ 21 | * | | | | | | |----| 22 | * | | | | | | |----| 23 | * +----+----+----+----+----+---------+ 24 | * finish 25 | * 26 | * 27 | * How many possible unique paths are there? 28 | * 29 | * Above is a 3 x 7 grid. How many possible unique paths are there? 30 | * 31 | * Note: m and n will be at most 100. 32 | * 33 | **********************************************************************************/ 34 | 35 | package main 36 | 37 | import ( 38 | "fmt" 39 | ) 40 | 41 | func uniquePath(m, n int) int { 42 | //create 2d arrays 43 | arr2d := make([][]int, m) 44 | 45 | for i := 0; i < len(arr2d); i++ { 46 | arr2d[i] = make([]int, n) 47 | } 48 | 49 | var MaxNum int 50 | for i := 0; i < m; i++ { 51 | for j := 0; j < n; j++ { 52 | if i == 0 && j == 0 { 53 | arr2d[i][j] = 0 54 | MaxNum = arr2d[i][j] 55 | } else { 56 | 57 | if i > 0 && j > 0 { 58 | arr2d[i][j] = arr2d[i-1][j] + arr2d[i][j-1] 59 | MaxNum = arr2d[i][j] 60 | } else { 61 | 62 | arr2d[i][j] = 1 63 | MaxNum = arr2d[i][j] 64 | 65 | } 66 | } 67 | 68 | } 69 | } 70 | fmt.Println(arr2d[0]) 71 | fmt.Println(arr2d[1]) 72 | fmt.Println(arr2d[2]) 73 | 74 | return MaxNum 75 | } 76 | 77 | func main() { 78 | fmt.Print(uniquePath(3, 7)) 79 | 80 | } 81 | -------------------------------------------------------------------------------- /validNumber.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/valid-number/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Validate if a given string is numeric. 8 | * 9 | * Some examples: 10 | * "0" => true 11 | * " 0.1 " => true 12 | * "abc" => false 13 | * "1 a" => false 14 | * "2e10" => true 15 | * 16 | * Note: It is intended for the problem statement to be ambiguous. 17 | * You should gather all requirements up front before implementing one. 18 | * 19 | **********************************************************************************/ 20 | 21 | package main 22 | 23 | import ( 24 | "fmt" 25 | "unicode" 26 | ) 27 | 28 | func isNumber(s string) bool { 29 | 30 | var dot bool 31 | var hasE bool 32 | var curr int 33 | var slen int = len(s) 34 | 35 | for _, c := range s { 36 | 37 | if unicode.IsSpace(c) { 38 | curr++ 39 | continue 40 | } 41 | 42 | break 43 | 44 | } 45 | 46 | if curr == slen { 47 | return false 48 | } 49 | 50 | if s[curr] == '+' || s[curr] == '-' { 51 | curr++ 52 | } 53 | 54 | // if !unicode.IsDigit(rune(s[curr])) { 55 | // return false 56 | // } else { 57 | // curr++ 58 | // } 59 | 60 | tmpSlice := s[curr:] 61 | 62 | for i := 0; i != len(tmpSlice); i++ { 63 | 64 | if tmpSlice[i] == '.' { 65 | if hasE == true || dot == true { 66 | return false 67 | } 68 | 69 | i++ 70 | if i == len(tmpSlice) { 71 | return true 72 | } 73 | // if !unicode.IsDigit(rune(tmpSlice[i])) { 74 | // return false 75 | // } 76 | 77 | dot = true 78 | continue 79 | 80 | } 81 | 82 | if tmpSlice[i] == 'e' { 83 | 84 | if hasE == true { 85 | return false 86 | } 87 | i++ 88 | if tmpSlice[i] == '+' || tmpSlice[i] == '-' { 89 | i++ 90 | } 91 | if !unicode.IsDigit(rune(tmpSlice[i])) { 92 | return false 93 | } 94 | hasE = true 95 | continue 96 | } 97 | 98 | if unicode.IsSpace(rune(tmpSlice[i])) { 99 | 100 | for _, c := range tmpSlice[i:] { 101 | if !unicode.IsSpace(c) { 102 | return false 103 | } 104 | 105 | } 106 | return true 107 | } 108 | 109 | if !unicode.IsDigit(rune(tmpSlice[i])) { 110 | return false 111 | } 112 | 113 | } 114 | 115 | return true 116 | } 117 | 118 | func main() { 119 | 120 | fmt.Println(isNumber("0.1")) 121 | fmt.Println(isNumber(" 0.1 ")) 122 | fmt.Println(isNumber("0")) 123 | fmt.Println(isNumber("abc")) 124 | fmt.Println(isNumber("1 a")) 125 | fmt.Println(isNumber("2.2e10")) 126 | fmt.Println(isNumber("-2.2e-4")) 127 | fmt.Println(isNumber("1.")) 128 | fmt.Println(isNumber(".981723")) 129 | 130 | } 131 | -------------------------------------------------------------------------------- /validPalindrome.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/valid-palindrome/ 2 | // Author : 18plusui 3 | // Date : 2016-03-03 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 8 | * 9 | * For example, 10 | * "A man, a plan, a canal: Panama" is a palindrome. 11 | * "race a car" is not a palindrome. 12 | * 13 | * Note: 14 | * Have you consider that the string might be empty? This is a good question to ask during an interview. 15 | * 16 | * For the purpose of this problem, we define empty string as valid palindrome. 17 | * 18 | * 19 | **********************************************************************************/ 20 | 21 | package main 22 | 23 | import ( 24 | "fmt" 25 | "regexp" 26 | "strings" 27 | ) 28 | 29 | func isPalindrome(s string) bool { 30 | s = removeNoise(s) 31 | var slen int = len(s) 32 | for i := 0; i < slen/2; i++ { 33 | fmt.Println("pre : ", s[i:i+1], "end : ", s[slen-i-1:slen-i]) 34 | if s[i:i+1] != s[slen-i-1:slen-i] { 35 | return false 36 | } 37 | } 38 | return true 39 | 40 | } 41 | 42 | func removeNoise(inputStr string) string { 43 | 44 | var validStr = regexp.MustCompile(`^[a-z]`) 45 | var unnoiseStr string 46 | var cnt int = 0 47 | 48 | inputStr = strings.ToLower(inputStr) 49 | for i := 0; i < len(inputStr); i++ { 50 | 51 | if validStr.MatchString(inputStr[i : i+1]) { 52 | 53 | unnoiseStr += inputStr[i : i+1] 54 | cnt++ 55 | } 56 | } 57 | 58 | return unnoiseStr 59 | 60 | } 61 | 62 | func main() { 63 | 64 | inputStr := "A man, a plan, a canal: Panama" 65 | fmt.Println(isPalindrome(inputStr)) 66 | 67 | } 68 | -------------------------------------------------------------------------------- /validParentheses.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/valid-parentheses/ 2 | // Author : 18plusui 3 | // Date : 2016-03-03 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', 8 | * determine if the input string is valid. 9 | * 10 | * The brackets must close in the correct order, "()" and "()[]{}" are all valid 11 | * but "(]" and "([)]" are not. 12 | * 13 | * 14 | **********************************************************************************/ 15 | 16 | package main 17 | 18 | import ( 19 | "fmt" 20 | ) 21 | 22 | func isValid(inputArr []string) bool { 23 | 24 | arrLen := len(inputArr) 25 | if arrLen == 0 { 26 | return false 27 | } 28 | 29 | var tmpCopy = make([]string, arrLen) 30 | for i, v := range inputArr { 31 | if v == "(" || v == "[" || v == "{" { 32 | tmpCopy[i] = v 33 | } else if v == ")" || v == "]" || v == "}" { 34 | if i == 0 || tmpCopy[i-1] == "" { 35 | return false 36 | } 37 | 38 | if (v == ")" && tmpCopy[i-1] == "(") || (v == "]" && tmpCopy[i-1] == "[") || 39 | (v == "}" && tmpCopy[i-1] == "{") { 40 | tmpCopy[i] = v 41 | } else { 42 | return false 43 | } 44 | } else { 45 | return false 46 | } 47 | fmt.Println(tmpCopy) 48 | } 49 | 50 | return true 51 | 52 | } 53 | 54 | func main() { 55 | inputArr := []string{"(", ")", "[", "}", "{", "]"} 56 | fmt.Println(isValid(inputArr)) 57 | } 58 | -------------------------------------------------------------------------------- /validSudoku.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/valid-sudoku/ 2 | // Author : 18plusui 3 | // Date : 2016-03-02 4 | 5 | /********************************************************************************** 6 | * 7 | * Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. 8 | * 9 | * The Sudoku board could be partially filled, where empty cells are filled with 10 | * the character '.'. 11 | * A partially filled sudoku which is valid. 12 | * 13 | * Note: 14 | * > A valid Sudoku board (partially filled) is not necessarily solvable. 15 | * Only the filled cells need to be validated. 16 | * 17 | **********************************************************************************/ 18 | 19 | package main 20 | 21 | import ( 22 | "fmt" 23 | ) 24 | 25 | const ( 26 | cnt int = 9 27 | ) 28 | 29 | func isValidSudoku(inputArr [9][9]int) bool { 30 | 31 | var row_mask [cnt][cnt]bool 32 | var col_mask [cnt][cnt]bool 33 | var partArea_mask [cnt][cnt]bool 34 | 35 | for r := 0; r < len(inputArr); r++ { 36 | for c := 0; c < len(inputArr[r]); c++ { 37 | 38 | if inputArr[r][c] == 0 { 39 | continue 40 | } 41 | idx := inputArr[r][c] - 1 42 | 43 | if row_mask[r][idx] == true { 44 | return true 45 | } 46 | row_mask[r][idx] = true 47 | 48 | if col_mask[c][idx] == true { 49 | return true 50 | } 51 | row_mask[c][idx] = true 52 | 53 | area := (r/3)*3 + (c / 3) 54 | if partArea_mask[area][idx] == true { 55 | return false 56 | } 57 | partArea_mask[area][idx] = true 58 | } 59 | } 60 | return true 61 | } 62 | 63 | func main() { 64 | inputArr := [9][9]int{ 65 | {0, 0, 6, 4, 8, 1, 3, 0, 0}, 66 | {0, 2, 0, 0, 0, 0, 0, 4, 0}, 67 | {7, 0, 0, 0, 0, 0, 0, 0, 9}, 68 | {8, 0, 0, 0, 9, 0, 0, 0, 4}, 69 | {6, 0, 0, 3, 4, 2, 0, 0, 1}, 70 | {5, 0, 0, 0, 6, 0, 0, 0, 2}, 71 | {3, 0, 0, 0, 0, 0, 0, 0, 5}, 72 | {0, 9, 0, 0, 0, 0, 0, 7, 0}, 73 | {0, 0, 5, 7, 1, 6, 2, 0, 0}, 74 | } 75 | 76 | fmt.Println(isValidSudoku(inputArr)) 77 | } 78 | -------------------------------------------------------------------------------- /validateBinarySearchTree.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/validate-binary-search-tree/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a binary tree, determine if it is a valid binary search tree (BST). 8 | * 9 | * Assume a BST is defined as follows: 10 | * 11 | * The left subtree of a node contains only nodes with keys less than the node's key. 12 | * The right subtree of a node contains only nodes with keys greater than the node's key. 13 | * Both the left and right subtrees must also be binary search trees. 14 | * 15 | * confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 16 | * 17 | * OJ's Binary Tree Serialization: 18 | * 19 | * The serialization of a binary tree follows a level order traversal, where '#' signifies 20 | * a path terminator where no node exists below. 21 | * 22 | * Here's an example: 23 | * 24 | * 1 25 | * / \ 26 | * 2 3 27 | * / 28 | * 4 29 | * \ 30 | * 5 31 | * 32 | * The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 33 | * 34 | * 35 | **********************************************************************************/ 36 | package main 37 | 38 | import ( 39 | "fmt" 40 | ) 41 | 42 | type Tree struct { 43 | Left *Tree 44 | Value int 45 | Right *Tree 46 | } 47 | 48 | func CreateTree(inputArr []int) *Tree { 49 | var t *Tree 50 | for _, v := range inputArr { 51 | 52 | t = insert(t, v) 53 | } 54 | return t 55 | } 56 | 57 | func insert(t *Tree, v int) *Tree { 58 | if t == nil { 59 | return &Tree{nil, v, nil} 60 | } 61 | 62 | if v < t.Value { 63 | 64 | t.Left = insert(t.Left, v) 65 | return t 66 | } 67 | 68 | t.Right = insert(t.Right, v) 69 | return t 70 | } 71 | 72 | func isValidBST(t *Tree) bool { 73 | 74 | fmt.Println(t.Value) 75 | 76 | if t.Left != nil && t.Right != nil { 77 | if t.Value < t.Left.Value || t.Value > t.Right.Value { 78 | 79 | return false 80 | } 81 | isValidBST(t.Left) 82 | isValidBST(t.Right) 83 | } else if t.Right != nil { 84 | if t.Value > t.Right.Value { 85 | 86 | return false 87 | } 88 | isValidBST(t.Right) 89 | } else if t.Left != nil { 90 | if t.Value < t.Left.Value { 91 | 92 | return false 93 | } 94 | isValidBST(t.Left) 95 | } 96 | 97 | return true 98 | } 99 | 100 | func main() { 101 | inputArr := []int{6, 4, 5, 1, 7, 8} 102 | t1 := CreateTree(inputArr) 103 | fmt.Println(isValidBST(t1)) 104 | fmt.Println(t1.Left.Right.Value) 105 | 106 | } 107 | -------------------------------------------------------------------------------- /wildcardMatching.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/wildcard-matching/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Implement wildcard pattern matching with support for '?' and '*'. 8 | * 9 | * '?' Matches any single character. 10 | * '*' Matches any sequence of characters (including the empty sequence). 11 | * 12 | * The matching should cover the entire input string (not partial). 13 | * 14 | * The function prototype should be: 15 | * bool isMatch(const char *s, const char *p) 16 | * 17 | * Some examples: 18 | * isMatch("aa","a") → false 19 | * isMatch("aa","aa") → true 20 | * isMatch("aaa","aa") → false 21 | * isMatch("aa", "*") → true 22 | * isMatch("aa", "a*") → true 23 | * isMatch("ab", "?*") → true 24 | * isMatch("aab", "c*a*b") → false 25 | * 26 | * 27 | **********************************************************************************/ 28 | package main 29 | 30 | import ( 31 | "fmt" 32 | ) 33 | 34 | func isMatch(inputStr string, matchStr string) bool { 35 | inputStart := 0 36 | matchStart := 0 37 | 38 | for inputStart != len(inputStr) { 39 | if matchStr[matchStart:matchStart+1] == "*" { 40 | matchStart++ 41 | if matchStart == len(matchStr) { 42 | return true 43 | } 44 | 45 | } else if matchStr[matchStart:matchStart+1] == "?" || 46 | inputStr[inputStart:inputStart+1] == matchStr[matchStart:matchStart+1] { 47 | matchStart++ 48 | inputStart++ 49 | if matchStart == len(matchStr) && matchStart == len(inputStr) { 50 | return true 51 | 52 | } 53 | } else if inputStart != 0 { 54 | inputStart++ 55 | 56 | } 57 | 58 | } 59 | 60 | return false 61 | 62 | } 63 | 64 | func main() { 65 | 66 | fmt.Println(isMatch("hello", "h??o")) 67 | } 68 | -------------------------------------------------------------------------------- /wordBreakI.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/word-break/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a string s and a dictionary of words dict, determine if s can be segmented 8 | * into a space-separated sequence of one or more dictionary words. 9 | * 10 | * For example, given 11 | * s = "leetcode", 12 | * dict = ["leet", "code"]. 13 | * 14 | * Return true because "leetcode" can be segmented as "leet code". 15 | * 16 | * 17 | **********************************************************************************/ 18 | package main 19 | 20 | import ( 21 | "fmt" 22 | ) 23 | 24 | func wordBreak(inputStr string, dict []string) bool { 25 | 26 | start := 0 27 | success := 0 28 | 29 | for i := 0; i <= len(inputStr); i++ { 30 | tmpSubstr := inputStr[start:i] 31 | for j := 0; j < len(dict); j++ { 32 | if tmpSubstr == dict[j] { 33 | start = i 34 | success++ 35 | if success == len(dict) { 36 | return true 37 | } 38 | } 39 | 40 | } 41 | 42 | } 43 | 44 | return false 45 | } 46 | 47 | func main() { 48 | fmt.Println(wordBreak("helloworld", []string{"hello", "world"})) 49 | 50 | } 51 | -------------------------------------------------------------------------------- /wordLadder.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/word-ladder/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Given two words (start and end), and a dictionary, find the length of shortest 8 | * transformation sequence from start to end, such that: 9 | * 10 | * Only one letter can be changed at a time 11 | * Each intermediate word must exist in the dictionary 12 | * 13 | * For example, 14 | * 15 | * Given: 16 | * start = "hit" 17 | * end = "cog" 18 | * dict = ["hot","dot","dog","lot","log"] 19 | * 20 | * As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", 21 | * return its length 5. 22 | * 23 | * Note: 24 | * 25 | * Return 0 if there is no such transformation sequence. 26 | * All words have the same length. 27 | * All words contain only lowercase alphabetic characters. 28 | * 29 | * 30 | **********************************************************************************/ 31 | package main 32 | 33 | import ( 34 | "fmt" 35 | "strings" 36 | ) 37 | 38 | var ( 39 | count int 40 | // tempMap map[string]int 41 | ) 42 | 43 | func wordLadder(start string, end string, inputArr []string, count int) { 44 | 45 | tempMap := make(map[string]int) 46 | tempMap[start] = count 47 | 48 | wordArr := strings.Split(start, "") 49 | 50 | for i := 0; i < len(inputArr); i++ { 51 | if exist(wordArr, 0, end, 0) == 2 { 52 | fmt.Println("length is : ", tempMap[start]+1) 53 | fmt.Println("success") 54 | break 55 | } 56 | 57 | if exist(wordArr, 0, inputArr[i], 0) == 2 { 58 | count++ 59 | tempMap[inputArr[i]] = count 60 | transfer := inputArr[i] 61 | inputArr[i] = "" 62 | wordLadder(transfer, end, inputArr, count) 63 | } 64 | 65 | } 66 | 67 | } 68 | 69 | func exist(inputArr []string, index int, match string, count int) int { 70 | 71 | for i := 0; i < len(inputArr); i++ { 72 | 73 | if index == len(inputArr) { 74 | break 75 | } 76 | 77 | if strings.ContainsAny(inputArr[index], match) { 78 | count++ 79 | } 80 | 81 | index++ 82 | 83 | } 84 | return count 85 | 86 | } 87 | 88 | func main() { 89 | 90 | inputArr := []string{"hot", "dot", "dog", "lot", "log"} 91 | wordLadder("hit", "cog", inputArr, 1) 92 | } 93 | -------------------------------------------------------------------------------- /wordPattern.go: -------------------------------------------------------------------------------- 1 | // Source : https://leetcode.com/problems/word-pattern/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /*************************************************************************************** 6 | * 7 | * Given a pattern and a string str, find if str follows the same pattern. 8 | * Here follow means a full match, such that there is a bijection between a letter in 9 | * pattern and a non-empty word in str. 10 | * 11 | * Examples: 12 | * 13 | * pattern = "abba", str = "dog cat cat dog" should return true. 14 | * pattern = "abba", str = "dog cat cat fish" should return false. 15 | * pattern = "aaaa", str = "dog cat cat dog" should return false. 16 | * pattern = "abba", str = "dog dog dog dog" should return false. 17 | * 18 | * Notes: 19 | * You may assume pattern contains only lowercase letters, and str contains lowercase 20 | * letters separated by a single space. 21 | * 22 | * Credits:Special thanks to @minglotus6 for adding this problem and creating all test 23 | * cases. 24 | * 25 | ***************************************************************************************/ 26 | package main 27 | 28 | import ( 29 | "fmt" 30 | "strings" 31 | ) 32 | 33 | func wordPattern(pattern string, str string) bool { 34 | patternMap := make(map[string]string) 35 | strMap := make(map[string]string) 36 | 37 | plen := len(pattern) 38 | strArr := strings.Split(str, " ") 39 | patternArr := strings.Split(pattern, "") 40 | 41 | if plen != len(strArr) { 42 | return false 43 | } 44 | 45 | for i := 0; i < plen; i++ { 46 | 47 | if _, ok := patternMap[patternArr[i]]; !ok { 48 | 49 | patternMap[patternArr[i]] = strArr[i] 50 | 51 | } 52 | 53 | if _, ok := strMap[strArr[i]]; !ok { 54 | 55 | strMap[strArr[i]] = patternArr[i] 56 | 57 | } 58 | 59 | if patternMap[patternArr[i]] != strArr[i] || strMap[strArr[i]] != patternArr[i] { 60 | fmt.Println("pattern map : ", patternMap) 61 | fmt.Println("string map : ", strMap) 62 | return false 63 | } 64 | } 65 | fmt.Println("pattern map : ", patternMap) 66 | fmt.Println("string map : ", strMap) 67 | return true 68 | } 69 | 70 | func main() { 71 | fmt.Println(wordPattern("ABBC", "dog cat cat dog")) 72 | } 73 | -------------------------------------------------------------------------------- /wordSearch.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/word-search/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * Given a 2D board and a word, find if the word exists in the grid. 8 | * 9 | * The word can be constructed from letters of sequentially adjacent cell, 10 | * where "adjacent" cells are those horizontally or vertically neighboring. 11 | * The same letter cell may not be used more than once. 12 | * 13 | * For example, 14 | * Given board = 15 | * 16 | * [ 17 | * ["ABCE"], 18 | * ["SFCS"], 19 | * ["ADEE"] 20 | * ] 21 | * 22 | * word = "ABCCED", -> returns true, 23 | * word = "SEE", -> returns true, 24 | * word = "ABCB", -> returns false. 25 | * 26 | * 27 | **********************************************************************************/ 28 | package main 29 | 30 | import ( 31 | "fmt" 32 | "strings" 33 | ) 34 | 35 | var boardStr []string 36 | var arr1dlen int 37 | var resVal bool 38 | 39 | func exist(board [][]string, word string) bool { 40 | if len(board) <= 0 || len(word) <= 0 { 41 | return false 42 | } 43 | 44 | mask := make([][]int, len(board)) 45 | for i := 0; i < 3; i++ { 46 | mask[i] = make([]int, len(board[i])) 47 | for j := 0; j < len(board[i]); j++ { 48 | mask[i][j] = 0 49 | } 50 | } 51 | 52 | for i := 0; i < len(board); i++ { 53 | for j := 0; j < len(board[i]); j++ { 54 | wordArr := strings.Split(word, "") 55 | 56 | if board[i][j] == wordArr[0] { 57 | if getExist(board, wordArr, 0, i, j, mask) { 58 | fmt.Println(mask) 59 | return true 60 | } 61 | } 62 | 63 | } 64 | } 65 | 66 | return false 67 | } 68 | 69 | func getExist(board [][]string, word []string, index int, row int, col int, mask [][]int) bool { 70 | 71 | i := row 72 | j := col 73 | 74 | if board[i][j] == word[index] && mask[i][j] == 0 { 75 | 76 | mask[i][j] = 1 77 | // fmt.Println("this is index length :", index, i, j) 78 | 79 | if index+1 == len(word) { 80 | return true 81 | } 82 | index++ 83 | 84 | if i+1 < len(board) && getExist(board, word, index, i+1, j, mask) || 85 | (i > 0 && getExist(board, word, index, i-1, j, mask)) || 86 | (j+1 < len(board[i]) && getExist(board, word, index, i, j+1, mask)) || 87 | (j > 0 && getExist(board, word, index, i, j-1, mask)) { 88 | return true 89 | } 90 | mask[i][j] = 0 91 | } 92 | 93 | return false 94 | } 95 | 96 | func main() { 97 | 98 | boardStr = []string{"ABCE", "SFCS", "ADEE"} 99 | arr2dLen := len(boardStr) 100 | 101 | board := make([][]string, arr2dLen) 102 | for i := 0; i < arr2dLen; i++ { 103 | arr1dlen = len(boardStr[i]) 104 | board[i] = make([]string, arr1dlen) 105 | board[i] = strings.Split(boardStr[i], "") 106 | } 107 | 108 | word := "ABCCED" 109 | fmt.Println(exist(board, word)) 110 | 111 | } 112 | -------------------------------------------------------------------------------- /zigzag.go: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/zigzag-conversion/ 2 | // Author : 18plusui 3 | // Date : 2016-03-07 4 | 5 | /********************************************************************************** 6 | * 7 | * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: 8 | * (you may want to display this pattern in a fixed font for better legibility) 9 | * 10 | * P A H N 11 | * A P L S I I G 12 | * Y I R 13 | * 14 | * And then read line by line: "PAHNAPLSIIGYIR" 15 | * 16 | * Write the code that will take a string and make this conversion given a number of rows: 17 | * 18 | * string convert(string text, int nRows); 19 | * 20 | * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 21 | * 22 | * 23 | **********************************************************************************/ 24 | package main 25 | 26 | import ( 27 | "fmt" 28 | "strings" 29 | ) 30 | 31 | var x int = 0 32 | var step int = 0 33 | var inputArr []string 34 | 35 | func zigzag(inputStr string, nRows int) string { 36 | if len(inputStr) < nRows || nRows <= 0 { 37 | return "you maybe not understand rule !!" 38 | } 39 | 40 | inputArr = strings.Split(inputStr, "") 41 | tmpArr := make([]string, nRows) 42 | 43 | for i := 0; i < len(inputArr); i++ { 44 | 45 | if x == nRows-1 { 46 | step = -1 47 | 48 | } 49 | 50 | if x == 0 { 51 | step = 1 52 | } 53 | 54 | fmt.Println("row number is : ", x) 55 | 56 | tmpArr[x] = tmpArr[x] + inputArr[i] 57 | x += step 58 | 59 | fmt.Println(tmpArr) 60 | 61 | } 62 | 63 | return "" 64 | } 65 | 66 | func main() { 67 | zigzag("helloworld", 4) 68 | } 69 | --------------------------------------------------------------------------------