翻译:对于M个查询,反转给定字符串的范围

2023年 8月 27日 75.5k 0

翻译:对于M个查询,反转给定字符串的范围

In this problem, we will perform M reverse queries on the given string according to the array values.

The naïve approach to solving the problem is to reverse each string segment according to the given array value.

The optimized approach uses the logic that when we reverse the same substring two times, we get the original string.

Problem statement − We have given an alpha string containing the alphabetical characters. Also, we have given an arr[] array of size M containing the positive integers. We need to perform the M operations on the given string and return the final string.

In each operation, we need to take the arr[i] and reveres the substring arr[i] to N − arr[i] + 1.

示例例子

输入

alpha = "pqrst"; arr = {2, 1};

登录后复制

输出

tqrsp

登录后复制

Explanation

  • 执行第一个查询后,字符串变为 'psrqt'。

  • 执行第二个查询后,我们得到了 'tqrsp'。

输入

− alpha = "pqrst"; arr = {1, 1};

登录后复制

输出

− ‘pqrst’

登录后复制

Explanation − 如果我们对同一个查询执行偶数次,我们会得到相同的字符串。

输入

− alpha = "pqrst"; arr = {1, 1, 1};

登录后复制

输出

− ‘tsrqp’

登录后复制

Explanation − If we perform the same query for an odd number of times, we get the reverse of the string.

Approach 1

In this approach, we will use the reverse() method to reverse the substring. We will take the starting and ending pointers using the given query and reverse the substring of the given string.

Algorithm

步骤 1 - 开始遍历查询数组。

第2步 - 使用arr[p] - 1初始化'left'变量。

Step 3 − Initialize the ‘right’ variable with str_len − arr[p] + 1.

Step 4 − Use the reverse() method to reverse the substring from left pointer to right pointer.

Example

#include
using namespace std;

void reverseStrings(string &alpha, int str_len, vector &arr, int arr_len){
// Traverse all queries
for (int p = 0; p < arr_len; p++){
// Get starting pointer
int left = arr[p] - 1;
// Ending pointer
int right = str_len - arr[p] + 1;
// Reverse the string
reverse(alpha.begin() + left, alpha.begin() + right);
}
}
int main(){
int str_len = 5;
string alpha = "pqrst";
int arr_len = 2;
vector arr = {2, 1};
reverseStrings(alpha, str_len, arr, arr_len);
cout

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论