From 6d35121858562425caeb0d4bfb35f5519d0b8b41 Mon Sep 17 00:00:00 2001 From: aucker Date: Sun, 16 Jun 2024 12:31:07 +0800 Subject: [PATCH] June16: Longest uncommon subsequence [M] use double loop for multiple strs, Enumerate Time: O(N^2 * l), Space: O(1) --- daily/June16.cpp | 54 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 daily/June16.cpp diff --git a/daily/June16.cpp b/daily/June16.cpp new file mode 100644 index 0000000..e33425d --- /dev/null +++ b/daily/June16.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; + +class Solution { + public: + /** + * @brief LC: 521: Longest Uncommon Subsequence + * Time: O(m+n), Space: O(1) + * + * @param a + * @param b + * @return int + */ + int findLUSlength(string a, string b) { + return a == b ? -1 : max(a.length(), b.length()); + } + + /** + * @brief LC: 522: Longest Uncommon Subsequences II + * There are multiple strs, not just one + * Time: O(n^2* l), l: avg size of strs, Space: O(1) + * + * @param strs + * @return int + */ + int findLUSlengthII(vector& strs) { + auto is_subseq = [](const string& lhs, const string& rhs) -> bool { + int pt_lhs = 0, pt_rhs = 0; + while (pt_lhs < lhs.size() && pt_rhs < rhs.size()) { + if (lhs[pt_lhs] == rhs[pt_rhs]) { + ++pt_lhs; + } + ++pt_rhs; + } + return pt_lhs == lhs.size(); + }; + + int len = strs.size(); + int ans = -1; + for (int i = 0; i < len; ++i) { + bool check = true; + for (int j = 0; j < len; ++j) { + if (i != j && is_subseq(strs[i], strs[j])) { + check = false; + break; + } + } + if (check) { + ans = max(ans, static_cast(strs[i].size())); + } + } + return ans; + } +}; \ No newline at end of file