查找信号到达字符串中所有位置所需的时间 - C++
c++server side programmingprogramming
在本教程中,我们将编写一个程序来计算信号到达字符串中所有位置所需的时间。让我用一个例子来解释一下。
我们将有一个只包含 s 和 p 字符的字符串。s 是一个 信号,p 是字符串中的 位置。信号从 s 开始,向左和向右传播。我们假设它需要一个单位的时间才能到达字符串中的下一个位置。我们的任务是计算将所有 位置 转换为 信号 所需的时间。
让我们看一些例子。
输入 − pppppspss
输出 − 5
输入 − pspspsps
输出 − 1
输入 − ssssss
输出 − 0
让我们看看解决问题所涉及的步骤。
初始化一个字符串和一个时间 (0)
遍历字符串。
计算连续的 p 个字符并将计数存储在变量中。
如果当前字符为 s 且 p 计数大于上次,则检查 s 是否存在于左侧。
如果 s 存在于两侧,则将计数分为两半,因为 s 可以双向移动。
重置 p 的计数。
示例
让我们看看代码。
#include <bits/stdc++.h> using namespace std; int timeToConvertToSignalString(string sample_string, int string_len) { int p_count = 0, time = 0; for (int i = 0; i <= string_len; i++) { if (sample_string[i] == 'p') { p_count++; } else { if (p_count > time) { bool is_present_left_side = false; if (((i - p_count) > 0) && (sample_string[i - p_count - 1] == 's')) { is_present_left_side = 1; } if (is_present_left_side) { p_count = ceil((double)p_count / 2); } time = max(time, p_count); } p_count = 0; } } return time; } int main() { string sample_string = "pppppspss"; int n = sample_string.size(); cout << timeToConvertToSignalString(sample_string, n) << endl; return 0; }
输出
如果你执行上述程序,那么你将得到以下结果。
5
尝试以不同的情况运行该程序并检查它。