C++字串中右側較大元素的數量
給定一個字串,我們需要計算每個字元右側較大元素的數量。讓我們來看一個例子。
輸入
string = "abc"
輸出
2 1 0
a 的右側有 2 個大於 a 的元素。
b 的右側有 1 個大於 b 的元素。
c 的右側有 0 個大於 c 的元素。
演算法
初始化字串。
初始化一個數組來跟蹤計數。
編寫兩個迴圈來迭代字串。
一次取一個字元,並將其與它後面的所有字元進行比較。
如果當前元素小於下一個元素,則遞增計數陣列中相應字元的計數。
列印所有字元的計數。
實現
以下是上述演算法在 C++ 中的實現
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; void countCharNextLargerElementsCount(string str) { int len = str.length(), count[len]; for (int i = 0; i < len; i++) { count[i] = 0; } for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if (str[i] < str[j]) { count[i]++; } } } for (int i = 0; i < len; i++) { cout << count[i] << " "; } cout << endl; } int main() { string str = "abcdefgh"; countCharNextLargerElementsCount(str); return 0; }Output
If you run the above code, then you will get the following result.
7 6 5 4 3 2 1 0
廣告