滑动窗口题目

题目描述:

计算两个字符串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,表示最短距离。

具体代码:

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;
}

 结果:

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值