查找信号到达字符串中所有位置所需的时间 - C++
在本教程中,我们将编写一个程序来计算信号到达字符串中所有位置所需的时间。让我用一个例子来解释。
我们将有一个字符串,其中只包含**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
尝试使用不同的情况运行程序并检查它。
结论
如果您在本教程中有任何疑问,请在评论部分提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP