C++程式查詢字元的最短距離


給定一個字串'a'和一個字元'char',任務是列印'char'到給定字串中每個字元的距離。距離陣列的大小與字串的大小相同,因為我們必須找到字元在給定字串中每個字元的距離。

例如

輸入-1

a = “tutorialspoint”

char = “o”

輸出:

[ 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3]

解釋:在給定的字串中,字元'o'到給定字串中每個字元的距離為[3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3]。

輸入-2

a = “programmer”

char = “r”

輸出

[1, 0, 1, 2, 0, 1, 2, 3, 4, 0 ]

解釋:在給定的字串中,'r'到給定字串中每個字元的距離為[1, 0, 1, 2, 0, 1, 2, 3, 4, 0]。

解決此問題的方法

解決此問題的暴力方法是在字串中找到給定字元的位置並存儲在陣列中。現在遍歷整個字串以及位置陣列以找到字元在給定字串中的最小距離。

  • 將字串和字元'char'作為輸入。
  • 函式distanceTochar(string a, char ch)以字串和字元作為輸入,並列印給定字元在給定字串中每個字元的距離。
  • 遍歷字串'a'並將給定字元的位置儲存到向量中。
  • 現在遍歷字串和位置陣列並計算字串中字元的距離。
  • 列印位置陣列。

示例

線上演示

#include<bits/stdc++.h>
using namespace std;
void shortestToChar(string a, char C) {
   vector < int > pos, dist;
   for (int i = 0; i < a.size(); i++) {
      if (a[i] == C)
         pos.push_back(i);
   }
   for (int i = 0; i < a.size(); i++) {
      int mn = INT_MAX;
      for (int j = 0; j < pos.size(); j++) {
         mn = min(mn, abs(pos[j] - i));
      }
      dist.push_back(mn);
   }
   for (auto i: dist) {
      cout << i << " ";
   }
}
int main() {
   string a = "tutorialspoint";
   char ch {
      'o'
   };
   shortestToChar(a, ch);
}

執行以上程式碼將生成以下輸出:

輸出

3 2 1 0 1 2 3 3 2 1 0 1 2 3

字串“tutorialspoint”中的字元'o'出現在索引3和索引10處。因此,如果我們計算其與其前後字元的最近距離,我們將得到距離為[3 2 1 0 1 2 3 3 2 1 0 1 2 3]。

更新於: 2021年2月23日

486 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.