Self-reflection caused by a common string title



Code View:

Here Insert Picture Description

General content:

第15行 —— 当int型数据错误地参与到了unsigned的数值大小的比较之中。
第18行 —— 以及之后的第20、27行,是否使用临时存储变量的问题。
第22行 —— 代码书写的赘余、无用功问题。
第24行 —— 借助临时变量的方式问题,像自己之前则是直接 iTemp=i; 和 jTemp=j;而不是如此巧妙的使用第三方实现索引变动。
第30行和第33行 —— 巧妙的设计往往不只是惊喜,还会有意外 —— 思维不够灵敏的话就会引发 k数值大小多1或差1的问题 —— 当然这也是 循环条件不再满足之后,控制循环的条件变量在循环体作用域内外使用时候的区别和值得小心之处。
第37行 —— 使用 vector 还得去 sort、得去除重复, 不如直接使用set —— 键值对的时候使用 map。
第38行和42行 —— 代码书写的严实与否的问题,太过疏散了如此分开 —— 本可以直接在定义的时候同时加以使用。
第39行 —— 通过输出检查代码是否如预期所想 —— 这是笔者从以前的一位大学同学那学来的冷门技能 —— 虽然是自己看了人家代码的意外收获,别人是不太会主动分享的、还得靠自己领悟。

**以上代码来自修改一位只识得姓名(不知真假)的19级学弟,经自己修改之后得以正常运行,并引发自己的一些思考。**

After the code optimization:

#include<iostream>
#include<string>
#include<set>
using namespace std;
int main(){

	string str1, str2;
	set<string> subsquSet;
	while (cin >> str1 >> str2){
		unsigned int max = 0;
		for (unsigned int i = 0; i < str1.size(); i++){
			for (unsigned int j = 0; j < str2.size(); j++){
				unsigned int k = 0;
				// 注意,下一行的 while循环的条件位置敏感,必须先是索引合法才能够去访问元素;
				while ( i + k < str1.size() && j + k < str2.length() && str1[i + k] == str2[j + k]) {
					k++;
				}
				subsquSet.insert(str1.substr(i, k)); // 等价实现: subsquSet.insert(str2.substr(j, k));
				if (max < k) { max = k; } 
			}
		}
		for (set<string>::iterator iter = subsquSet.begin(); iter != subsquSet.end(); ++iter)
		{
			// cout << *iter << endl; // 输出所有子串(set集合的元素)
			if ((*iter).size() == max) {
				cout << *iter << endl;
				break;
			}
		}
		subsquSet.clear(); // 记得重置集合为空;
	}
	return 0;
}

postscript:

For exchanges, can leave a message in the comments section or send a private letter, of course, can also e-mail or add a friend (as long as the author line)
[email protected]
For forwarding, please indicate the source

Also attach your blog post: the longest common substring Detailed with the longest common subsequence

2019/11/22 23:12

Further optimization of the output code of the container:

for (auto iter : subsquSet )
		{
			// cout << iter << endl; // 输出所有子串(set集合的元素)包含空串
			if ((iter).size() == max) {
				cout << iter << endl;
				break;
			}
		}
注意区分:迭代器返回的是 地址,需要地址解析符* 读取数据,而for each则是直接遍历各个元素数据本身。
故:推荐将其中代码的 iter 改写为 item。

2019/11/23 16:50

Published 89 original articles · won praise 159 · views 50000 +

Guess you like

Origin blog.csdn.net/I_love_you_dandan/article/details/103208486