Skip to content

Instantly share code, notes, and snippets.

@Crspy
Last active May 22, 2019 23:05
Show Gist options
  • Select an option

  • Save Crspy/c7cab80ab03a9bfed36aea4fb51adc9d to your computer and use it in GitHub Desktop.

Select an option

Save Crspy/c7cab80ab03a9bfed36aea4fb51adc9d to your computer and use it in GitHub Desktop.
Find longest common sub sequence in two strings.
#include <string>
std::string LongestSubSeq(std::string s1, std::string s2)
{
// space complexity O(2 *LengthOfLongestString)
// time Complexity O(s1Length*s2Length)
size_t Len = s1.length() > s2.length() ? s1.length() : s2.length();
std::string result,temp;
result.reserve(Len);
temp.reserve(Len);
for (size_t s1idx{ 0 }; s1idx < s1.length(); ++s1idx)
{
const char currCh = s1[s1idx];
size_t s2firstPos = s2.find(currCh, 0);
if (s2firstPos == s2.npos) continue;
temp.clear();
temp.push_back(currCh);
size_t s2nextPos = s2firstPos + 1;
for (size_t s1subIdx{ s1idx + 1 }; s1subIdx < s1.length(); ++s1subIdx)
{
const char nextCh = s1[s1subIdx];
size_t s2subPos = s2.find(nextCh, s2nextPos);
if (s2subPos != s2.npos)
{
temp.push_back(nextCh);
s2nextPos = s2subPos + 1;
}
}
if (temp.length() > result.length())
{
result = temp;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment