邓心一 há 6 anos atrás
pai
commit
ab9fe1e107

+ 43 - 0
easy/687.longest-univalue-path.go

@@ -0,0 +1,43 @@
+/**
+ * Definition for a binary tree node.
+ * type TreeNode struct {
+ *     Val int
+ *     Left *TreeNode
+ *     Right *TreeNode
+ * }
+ */
+func longestUnivaluePath(root *TreeNode) int {
+	max := 0
+	if root == nil {
+		return max
+	}
+	helper(root, &max)
+	return max - 1
+}
+
+func helper(root *TreeNode, max *int) int {
+	l, r := 0, 0
+	if root.Left != nil {
+		l = helper(root.Left, max)
+		if root.Left.Val != root.Val {
+			l = 0
+		}
+	}
+	if root.Right != nil {
+		r = helper(root.Right, max)
+		if root.Right.Val != root.Val {
+			r = 0
+		}
+	}
+	if *max < 1+l+r {
+		*max = 1 + l + r
+	}
+	return 1 + maxInt(l, r) // !!important
+}
+
+func maxInt(x, y int) int {
+	if x < y {
+		return y
+	}
+	return x
+}

+ 16 - 0
easy/693.binary-number-with-alternating-bits.go

@@ -0,0 +1,16 @@
+func hasAlternatingBitsNaive(n int) bool {
+	for mask := ^(n & 1); n != 0; n >>= 1 {
+		next := n & 1
+		if mask == next {
+			return false
+		}
+		mask = next
+	}
+	return true
+}
+
+func hasAlternatingBits(n int) bool {
+	for n ^= n >> 1; n != 0 && n&1 == 1; n >>= 1 {
+	}
+	return n == 0
+}

+ 21 - 0
easy/696.count-binary-substrings.go

@@ -0,0 +1,21 @@
+func countBinarySubstrings(s string) int {
+	n, cnt := len(s), 0
+	if n < 2 {
+		return cnt
+	}
+	for i := 0; i < n-1; i++ {
+		if s[i] == s[i+1] {
+			continue
+		}
+		cnt++
+		for j := 1; 0 <= i-j && i+j+1 < n; j++ {
+			if s[i-j] == s[i] && s[i+j+1] == s[i+1] {
+				cnt++
+			} else {
+				i += j - 1
+				break
+			}
+		}
+	}
+	return cnt
+}