aboutsummaryrefslogtreecommitdiff
path: root/works/solutions/leetcode/cpp/395.cpp
diff options
context:
space:
mode:
authorYuqian Yang <crupest@crupest.life>2025-02-12 15:55:21 +0800
committerYuqian Yang <crupest@crupest.life>2025-02-12 16:04:50 +0800
commit93ea69f427e3d8165d34bd6ca7b533666884f307 (patch)
tree22fcaec20fcdad22afd01c4214ca5301e304e15f /works/solutions/leetcode/cpp/395.cpp
parent1ecfd0ab7f1f511268fd6404dbc110c3c277b48c (diff)
parenteb8beb49117289ba9181cbefe647c4aa44e6a0b1 (diff)
downloadcrupest-93ea69f427e3d8165d34bd6ca7b533666884f307.tar.gz
crupest-93ea69f427e3d8165d34bd6ca7b533666884f307.tar.bz2
crupest-93ea69f427e3d8165d34bd6ca7b533666884f307.zip
import(solutions): IMPORT crupest/solutions COMPLETE.
Diffstat (limited to 'works/solutions/leetcode/cpp/395.cpp')
-rw-r--r--works/solutions/leetcode/cpp/395.cpp56
1 files changed, 56 insertions, 0 deletions
diff --git a/works/solutions/leetcode/cpp/395.cpp b/works/solutions/leetcode/cpp/395.cpp
new file mode 100644
index 0000000..d45eee9
--- /dev/null
+++ b/works/solutions/leetcode/cpp/395.cpp
@@ -0,0 +1,56 @@
+#include <array>
+#include <string>
+
+using std::string;
+
+class Solution {
+public:
+ static int dfs(const std::string &s, int start, int end, int k) {
+ if (end - start < k) {
+ return 0;
+ }
+
+ std::array<int, 26> counts{0};
+
+ for (int i = start; i < end; i++) {
+ counts[s[i] - 'a']++;
+ }
+
+ int max = -1;
+
+ for (char c = 'a'; c <= 'z'; c++) {
+ int count = counts[c - 'a'];
+
+ if (count > 0 && count < k) {
+ int sub_start = start;
+
+ for (int i = start; i < end; i++) {
+ if (s[i] == c) {
+ if (sub_start != i) {
+ max = std::max(dfs(s, sub_start, i, k), max);
+ }
+ sub_start = i + 1;
+ }
+ }
+
+ if (sub_start != end) {
+ max = std::max(dfs(s, sub_start, end, k), max);
+ }
+
+ break; // This is vital.
+ }
+ }
+
+ if (max == -1)
+ return end - start;
+ else
+ return max;
+ }
+
+ int longestSubstring(string s, int k) { return dfs(s, 0, s.size(), k); }
+};
+
+int main() {
+ Solution{}.longestSubstring("aaaaaaaaaaaabcdefghijklmnopqrstuvwzyz", 3);
+ return 0;
+}