Skip to content

Commit

Permalink
Add solution and test-cases for problem 1400
Browse files Browse the repository at this point in the history
  • Loading branch information
0xff-dev committed Jan 11, 2025
1 parent d569e0c commit 2856c94
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 11 deletions.
36 changes: 36 additions & 0 deletions leetcode/1301-1400/1400.Construct-K-Palindrome-Strings/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# [1400.Construct K Palindrome Strings][title]

## Description
Given a string `s` and an integer `k`, return `true` if you can use all the characters in `s` to construct `k` palindrome strings or `false` otherwise.

**Example 1:**

```
Input: s = "annabelle", k = 2
Output: true
Explanation: You can construct two palindromes using all characters in s.
Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"
```

**Example 2:**

```
Input: s = "leetcode", k = 3
Output: false
Explanation: It is impossible to construct 3 palindromes using all the characters of s.
```

**Example 3:**

```
Input: s = "true", k = 4
Output: true
Explanation: The only possible solution is to put each character in a separate string.
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/construct-k-palindrome-strings/
[me]: https://github.com/kylesliu/awesome-golang-algorithm
27 changes: 25 additions & 2 deletions leetcode/1301-1400/1400.Construct-K-Palindrome-Strings/Solution.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(s string, k int) bool {
if len(s) < k {
return false
}
count := [26]int{}
for _, b := range s {
count[b-'a']++
}
odd, even := 0, 0
for _, n := range count {
if n == 0 {
continue
}
even += n
if n&1 == 1 {
odd++
}
}
if odd > k {
return false
}
if k == odd {
return true
}
return k <= even
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,31 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
s string
k int
expect bool
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", "annabelle", 2, true},
{"TestCase2", "leetcode", 3, false},
{"TestCase3", "true", 4, true},
}

// 开始测试
for i, c := range cases {
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
got := Solution(c.inputs)
got := Solution(c.s, c.k)
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, got, c.inputs)
t.Fatalf("expected: %v, but got: %v, with inputs: %v %v",
c.expect, got, c.s, c.k)
}
})
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}

0 comments on commit 2856c94

Please sign in to comment.