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

更新於: 2020年10月9日

139 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.