-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3760-MaximumSubstringsWithDistinctStart.go
More file actions
88 lines (76 loc) · 2.38 KB
/
3760-MaximumSubstringsWithDistinctStart.go
File metadata and controls
88 lines (76 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
// 3760. Maximum Substrings With Distinct Start
// You are given a string s consisting of lowercase English letters.
// Return an integer denoting the maximum number of substrings you can split s into such that each substring starts with a distinct character
// (i.e., no two substrings start with the same character).
// Example 1:
// Input: s = "abab"
// Output: 2
// Explanation:
// Split "abab" into "a" and "bab".
// Each substring starts with a distinct character i.e 'a' and 'b'. Thus, the answer is 2.
// Example 2:
// Input: s = "abcd"
// Output: 4
// Explanation:
// Split "abcd" into "a", "b", "c", and "d".
// Each substring starts with a distinct character. Thus, the answer is 4.
// Example 3:
// Input: s = "aaaa"
// Output: 1
// Explanation:
// All characters in "aaaa" are 'a'.
// Only one substring can start with 'a'. Thus, the answer is 1.
// Constraints:
// 1 <= s.length <= 10^5
// s consists of lowercase English letters.
import "fmt"
import "math/bits"
func maxDistinct(s string) int {
res, mp := 0, make([]bool,26)
for _, c := range s {
c -= 'a'
if !mp[c] {
mp[c] = true
res++
}
}
return res
}
func maxDistinct1(s string) int {
set := 0
for _, c := range s {
set |= 1 << (c - 'a')
}
return bits.OnesCount(uint(set))
}
func main() {
// Example 1:
// Input: s = "abab"
// Output: 2
// Explanation:
// Split "abab" into "a" and "bab".
// Each substring starts with a distinct character i.e 'a' and 'b'. Thus, the answer is 2.
fmt.Println(maxDistinct("abab")) // 2
// Example 2:
// Input: s = "abcd"
// Output: 4
// Explanation:
// Split "abcd" into "a", "b", "c", and "d".
// Each substring starts with a distinct character. Thus, the answer is 4.
fmt.Println(maxDistinct("abcd")) // 4
// Example 3:
// Input: s = "aaaa"
// Output: 1
// Explanation:
// All characters in "aaaa" are 'a'.
// Only one substring can start with 'a'. Thus, the answer is 1.
fmt.Println(maxDistinct("aaaa")) // 1
fmt.Println(maxDistinct("leetcode")) // 6
fmt.Println(maxDistinct("bluefrog")) // 8
fmt.Println(maxDistinct1("abab")) // 2
fmt.Println(maxDistinct1("abcd")) // 4
fmt.Println(maxDistinct1("aaaa")) // 1
fmt.Println(maxDistinct1("leetcode")) // 6
fmt.Println(maxDistinct1("bluefrog")) // 8
}