ในปัญหานี้ เราได้รับสตริง str และ Q คำถาม (queries) ที่ประกอบด้วยค่าสองค่า a และ b ภารกิจคือการสร้างโปรแกรมเพื่อแก้ปัญหา Queries for characters in a repeated string ใน C++
คำอธิบายปัญหา
เพื่อแก้แต่ละคำถาม เราต้องตรวจสอบว่าตัวอักษรที่ index a และ b เป็นตัวอักษรเดียวกันหรือไม่ และคืนค่าตามนั้น
ตัวอย่างเพื่อเข้าใจปัญหา:
อินพุต: str = "tutorialspoint"
Q = 2
Query = {{0, 2}, {4, 7}}
เอาต์พุต: Repeated / Not Repeated
คำอธิบาย
สำหรับ Query 1 ตัวอักษรที่ index 0 คือ t และตัวอักษรที่ index 2 ก็คือ t ทั้งสองเป็นตัวอักษรเดียวกัน
สำหรับ Query 2 ตัวอักษรที่ index 4 คือ r และตัวอักษรที่ index 7 คือ l ทั้งสองไม่ใช่ตัวอักษรเดียวกัน
แนวทางแก้ปัญหา
เพื่อแก้ปัญหา เราจะตรวจสอบความเท่าเทียมของสมาชิกที่ index a และ b หาก index ใด index หนึ่งมากกว่าความยาวของสตริง เราจะหาค่า (index % len) เพื่อหา index ของตัวอักษร และใช้ index ใหม่สำหรับการเปรียบเทียบ
ตัวอย่างโค้ด
#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