diff --git a/leetcode/0392/solution.hpp b/leetcode/0392/solution.hpp index 92950f0..f052937 100644 --- a/leetcode/0392/solution.hpp +++ b/leetcode/0392/solution.hpp @@ -1,19 +1,18 @@ #include -class Solution { -public: - bool isSubsequence(std::string s, std::string t) { +// 方法1:双指针 +struct Solution { + static bool isSubsequence(const std::string &s, const std::string &t) { + std::size_t ss{s.size()}, ts{t.size()}; if (s.size() > t.size()) { return false; } - std::size_t pos{0}; - for (char ch : s) { - pos = t.find(ch, pos); - if (pos == t.npos) { - return false; + std::size_t si{0}; + for (std::size_t ti{0}; si < ss && ti < ts; ++ti) { + if (s[si] == t[ti]) { + ++si; } - ++pos; } - return true; + return si == ss; } }; diff --git a/leetcode/0392/test.cpp b/leetcode/0392/test.cpp index 47a1f06..4bb8934 100644 --- a/leetcode/0392/test.cpp +++ b/leetcode/0392/test.cpp @@ -41,4 +41,5 @@ void Expect(const TestCase &tc) { TEST_Y(LeetCode392, Example1); TEST_Y(LeetCode392, Example2); +TEST_Y(LeetCode392, Regression1); } // namespace diff --git a/leetcode/0392/test_suite.yaml b/leetcode/0392/test_suite.yaml index 795a751..64f65bb 100644 --- a/leetcode/0392/test_suite.yaml +++ b/leetcode/0392/test_suite.yaml @@ -9,3 +9,9 @@ example2: s: "axc" t: "ahbgdc" expected: false + +regression1: + input: + s: "abc" + t: "" + expected: false diff --git a/leetcode/2011/solution.hpp b/leetcode/2011/solution.hpp index b296321..88906e6 100644 --- a/leetcode/2011/solution.hpp +++ b/leetcode/2011/solution.hpp @@ -4,8 +4,7 @@ // 方法1:模拟 namespace approach1 { -class Solution { -public: +struct Solution { static int finalValueAfterOperations(const std::vector &operations) { int res{0}; for (const auto &op : operations) { @@ -20,10 +19,9 @@ class Solution { }; } // namespace approach1 -// 方法2:计数 +// 方法2:计数 + 数学推导 namespace approach2 { -class Solution { -public: +struct Solution { static int finalValueAfterOperations(const std::vector &operations) { auto isInc{[](const std::string &op) { return op[1] == '+'; }}; return 2 * std::ranges::count_if(operations, isInc) - operations.size();