dengxinyi 6 years ago
parent
commit
68ee81143f

+ 27 - 0
medium/583.delete-operation-for-two-strings.go

@@ -0,0 +1,27 @@
+func minDistance(word1 string, word2 string) int {
+	// dp[i][j] means the LCS of s1[0:i] && s2[0:j],
+	// then if s1[i] == s2[j], dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j]+1)
+	// else dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
+	m, n := len(word1), len(word2)
+	dp := make([][]int, m+1)
+	for i := range dp {
+		dp[i] = make([]int, n+1)
+	}
+	for i := range word1 {
+		for j := range word2 {
+			if word1[i] == word2[j] {
+				dp[i+1][j+1] = maxInt(dp[i+1][j+1], dp[i][j]+1)
+			} else {
+				dp[i+1][j+1] = maxInt(dp[i][j+1], dp[i+1][j])
+			}
+		}
+	}
+	return m + n - 2*dp[m][n]
+}
+
+func maxInt(x, y int) int {
+	if x < y {
+		return y
+	}
+	return x
+}

+ 49 - 0
medium/592.fraction-addition-and-subtraction.go

@@ -0,0 +1,49 @@
+type pair struct {
+	_1 int
+	_2 int
+}
+
+func (p1 *pair) add(p2 pair) {
+	if p1._1 == 0 {
+		*p1 = p2
+	} else {
+		p1._1 = p1._1*p2._2 + p2._1*p1._2
+		p1._2 *= p2._2
+	}
+}
+
+func fractionAddition(expression string) string {
+	beg, end, n := 0, 1, len(expression)
+	var sum pair
+	for end < n {
+		for end = beg + 1; end < n && expression[end] != '+' && expression[end] != '-'; end++ {
+		}
+		p := str2frac(expression[beg:end])
+		sum.add(p)
+		beg = end
+	}
+	i := gcd(abs(sum._1), sum._2)
+	return fmt.Sprintf("%d/%d", sum._1/i, sum._2/i)
+}
+
+func gcd(a, b int) int {
+	if b == 0 {
+		return a
+	}
+	return gcd(b, a%b)
+}
+
+func str2frac(s string) (p pair) {
+	strs := strings.Split(s, "/")
+	p._1, _ = strconv.Atoi(strs[0])
+	p._2, _ = strconv.Atoi(strs[1])
+	return
+}
+
+func abs(x int) int {
+	if x < 0 {
+		return -x
+	}
+	return x
+}
+