滑动窗口题目

题目描述:

计算两个字符串str1和str2在给定的含有n个元素的字符串数组strs中出现的最短距离。

详细解释:

  1. 定义整数变量n,用于存储字符串数组strs的长度。
  2. 定义一个vector<string>类型的变量strs,用于存储输入的字符串。
  3. 定义两个字符串变量str1和str2,用于存储输入的两个字符串。
  4. 使用循环,从输入中读取字符串str1和str2,并将它们存储在str1和str2中。
  5. 使用循环,从输入中读取n个字符串,并将它们存储在strs中。
  6. 定义两个整数变量count1和count2,用于存储字符串str1和str2在strs中出现的下标。
  7. 定义一个整数变量ret,用于存储最短距离。
  8. 使用循环,遍历字符串数组strs。
  9. 如果当前字符串等于str1,则将count1设置为当前下标i。
  10. 如果当前字符串等于str2,则将count2设置为当前下标i。
  11. 如果count1和count2都不等于-1,则计算它们之间的距离,并将其与当前的ret进行比较。
  12. 如果ret等于n,则输出-1,表示没有找到最短距离。
  13. 否则,输出ret,表示最短距离。

具体代码:

cpp 复制代码
int main() {
	int n;
	cin >> n;
	vector<string> strs;
	string str1, str2;
	cin >> str1 >> str2;
	for (int i = 0; i < n; i++) {
		string str;
		cin >> str;
		strs.push_back(str);
	}

	int count1 = -1, count2 = -1;
	int ret = n;
	for (int i = 0; i < n; i++) {
		if (strs[i] == str1 ) {
			count1 = i;
		}
		if (strs[i] == str2 ) {
			count2 = i;
		}
		if (count1 != -1 && count2 != -1 ) {
			int count = abs(count1 - count2);
			
			ret = min(ret,count);
		}
	}
	if (ret == n)
		std::cout << -1;
	else
		std::cout << ret;

	

	return 0;
}

结果:

相关推荐
QiLinkOS7 小时前
QiLink OS的失败数据共享平台的运作模式是否适用于所有行业?
android·开发语言·人工智能·算法·重构·开源
C++ 老炮儿的技术栈7 小时前
MFC 自定义纯色居中文字进度条控件
c语言·数据库·c++·windows·算法·c·visual studio
researcher-Jiang7 小时前
Manacher算法学习与应用
c++·学习·算法
码完就睡7 小时前
数据结构——串的模式匹配算法(BF算法、KMP算法)
数据结构·算法
tachibana27 小时前
hot100 排序链表(148)
java·数据结构·算法·leetcode·链表
林泽毅7 小时前
Qwen3.5 DPO 模型对齐实战(pytrio训练版)
人工智能·python·算法
imuliuliang7 小时前
算法中的随机化思想及其复杂度收益评估的技术7
算法
不能跑的代码不是好代码7 小时前
二叉树从基础概念到LeetCode实战
算法·leetcode
凯瑟琳.奥古斯特8 小时前
二分查找解力扣1011最优运载能力
开发语言·c++·算法·leetcode·职场和发展
学计算机的计算基8 小时前
二叉树算法下篇:递归核心技巧与高频面试题详解
java·笔记·算法