Analyzing two longest common string sequence (space complexity 1)

Here Insert Picture Description

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str1;
	string str2;
	while (cin >> str1 >> str2)
	{
		if (str1.size() < str2.size())
			swap(str1, str2);
		int length1 = str1.size();
		int length2 = str2.size();
		if (length1 == 0 || length2 == 0)
		{
			cout << 0 << endl;
			return 0;
		}
		int maxsize = 0;
		int k = 0;
		for (int i = 0; i < length1; ++i)
		{
			for (int j = 0; j < length2;++j)
			{
				int flag = 0;
				k = i;
				int count = 0;
				while (k < length1 && j < length2 &&str1[k] == str2[j] || str1[k] == str2[j] - 32 || str1[k] == str2[j] + 32)
				{
					++k;
					++j;
					flag = 1;
					++count;
				}
				k = i;
				if (count > maxsize)
				{
					maxsize = count;
				}
				if (flag == 1)
					--j;
			}
		}
		cout << maxsize << endl;
		maxsize = 0;
	}
	return 0;
}

Have to say for a long time to write this code, complex space of 1, but the details of too many cattle off test cases can not see, I too hard.
For code analysis:
1.
Let str1 always the longest string is stored in
Here Insert Picture Description
the special case determined but it looks like bovine passenger does not use case
Here Insert Picture Description
followed by a double loop, so long strings do outside cycling conditions, which do short string the cycling conditions
Here Insert Picture Description

Published 230 original articles · won praise 28 · views 9335

Guess you like

Origin blog.csdn.net/weixin_43767691/article/details/103302337