C++中重复字符串中字符的查询
在这个问题中,我们给定一个字符串str和Q个查询,每个查询包含两个值a和b。我们的任务是创建一个程序来解决C++中重复字符串中字符的查询。
问题描述
为了解决每个查询,我们需要检查索引a和b处的字符是否相同,并相应地返回值。
让我们举个例子来理解这个问题:
输入: str = “tutorialspoint”
Q = 2
查询 = {{0, 2}, {4, 7}}
输出:重复
不重复
解释
对于查询1,索引0处的字符是t,索引2处的字符是t。两者是相同的字符。
对于查询1,索引4处的字符是r,索引7处的字符是l。两者不是相同的字符。
解决方案
为了解决这个问题,我们将简单地检查索引a和b处的元素是否等价。如果任何索引大于字符串的长度,我们将找到(index%len)的值,以获得字符的索引。然后使用新的索引进行比较。
示例
#include <iostream>
#include <string>
using namespace std;
bool isrepeated(string str, int len, int a, int b){
if(a > len)
a %= len;
if(b > len)
b %= len;
if(str[a] == str[b])
return true;
else
return false;
}
int main(){
string str = "tutorialspoint";
int len = str.length();
int Q = 3;
int query[Q][2] = {{0, 2}, {3, 32}, {5, 18}};
for(int i = 0; i < Q; i++){
if(isrepeated(str, len, query[i][0], query[i][1]))
cout<<"Character is repeated in both the index values"<<endl;
else
cout<<"Character is not repeated in both the index values"<<endl;
}
return 0;
}输出
Character is repeated in both the index values Character is not repeated in both the index values Character is not repeated in both the index values
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP