diff --git a/algorithm/array/CMakeLists.txt b/algorithm/array/CMakeLists.txt index 4acba2e5..10693d04 100644 --- a/algorithm/array/CMakeLists.txt +++ b/algorithm/array/CMakeLists.txt @@ -23,7 +23,7 @@ list(APPEND leetcode_order 905 908 922 941 942) list(APPEND leetcode_order 944 977 985 986 989) list(APPEND leetcode_order 999 1010 1013 1030 1051) list(APPEND leetcode_order 1089 1108 1170 1184 1200) -list(APPEND leetcode_order 1217 1329 1360 1365) +list(APPEND leetcode_order 1217 1329 1360 1365 1371) LIST(TRANSFORM leetcode_order PREPEND leetcode_) set(dependencies ${dependencies} ${leetcode_order}) diff --git a/algorithm/array/leetcode_1371.cpp b/algorithm/array/leetcode_1371.cpp new file mode 100644 index 00000000..c7820b55 --- /dev/null +++ b/algorithm/array/leetcode_1371.cpp @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +/* +CS203_DSAA_template + +Copyright (C) 2023 nanoseeds + +*/ +#include "leetcode_1371_test.hpp" + +namespace leetcode_1371 { +// 把寻找最长字串的问题, 转化成在[0,i)之间寻找一个点, [0,point), [0,i)上, 元音字母的odd/even相同 +// 经典的把O(N^2)的组合问题 拆分成O(N)的(0,N)之后两者作差 +int32_t leetcode_1371::findTheLongestSubstring(const string &s) { + constexpr const auto chnums{26}; + constexpr const std::array nums{ + 0b1, 0, 0, 0, 0b10, + 0, 0, 0, 0b100, 0, + 0, 0, 0, 0, 0b1000, + 0, 0, 0, 0, 0, + 0b10000, 0, 0, 0, 0, + 0 + }; + constexpr const auto specials{5}; + std::array map{-1,}; // key, even-odd值 + for (size_t i{1}; i < (1 << specials); ++i) { + map[i] = 0x3f3f3f3f; + } + // value latest prefix + int32_t distance{0}; + for (int32_t i{0}, count_num{0}; i < static_cast(s.size()); ++i) { + const auto ch{s[i]}; + count_num ^= (nums[ch - 'a']); + map[count_num] = std::min(map[count_num], i); // 把值赋给最早的 + if (map[count_num] != 0x3f3f3f3f) { + distance = std::max(distance, i - map[count_num]); + } + } + return distance; +} + +} diff --git a/algorithm/array/leetcode_1371_test.hpp b/algorithm/array/leetcode_1371_test.hpp new file mode 100644 index 00000000..4187378b --- /dev/null +++ b/algorithm/array/leetcode_1371_test.hpp @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +/* +CS203_DSAA_template + +Copyright (C) 2023 nanoseeds + +*/ +//@Tag array +//@Tag 数组 +#ifndef CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1371_TEST_HPP +#define CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1371_TEST_HPP + +#include +#include +#include +#include +#include + +namespace leetcode_1371 { +using std::vector; + +namespace leetcode_1371 { +int32_t findTheLongestSubstring(const std::string &s); +} + +TEST_CASE("test case 1-1 {test_1371}", "{test_1371}") { + constexpr const char*const input{"leetcodeisgreat"}; + constexpr const auto output{5}; + CHECK(output == leetcode_1371::findTheLongestSubstring(input)); +} + +} +#endif //CS203_DSAA_TEMPLATE_ALGORITHM_ARRAY_LEETCODE_1371_TEST_HPP