From 317c821cc374b0df502ea821a957d0978801d3e8 Mon Sep 17 00:00:00 2001 From: Shivesh Kumar <87690329+shivesh41kr@users.noreply.github.com> Date: Mon, 10 Oct 2022 16:45:52 +0530 Subject: [PATCH] LeetCode_1048_longest_string_chain.cpp LeetCode Problem No. - 1048 solution --- .../1048_longest_string_chain.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Leetcode problems/1048_longest_string_chain.cpp diff --git a/Leetcode problems/1048_longest_string_chain.cpp b/Leetcode problems/1048_longest_string_chain.cpp new file mode 100644 index 00000000..0f7d71b8 --- /dev/null +++ b/Leetcode problems/1048_longest_string_chain.cpp @@ -0,0 +1,25 @@ +class Solution +{ +public: + int longestStrChain(vector &words) + { + unordered_map dp; + int ans = 0; + sort(words.begin(), words.end(), sortByLength); + for (string word : words) + { + for (int i = 0; i < word.length(); i++) + { + string predecessor = word.substr(0, i) + word.substr(i + 1); + dp[word] = max(dp[word], dp[predecessor] + 1); + } + ans = max(ans, dp[word]); + } + return ans; + } + + static bool sortByLength(string &s1, string &s2) + { + return s1.length() < s2.length(); + } +};