C ++中字符串右侧较大元素的数量
在本教程中,我们将编写一个程序来查找字符串右侧较大元素的数量。
让我们看看解决问题的步骤。
初始化字符串。
初始化一个数组以跟踪计数。
编写两个循环来遍历字符串。
一次取一个字符并将其与后面的所有字符进行比较。
如果当前元素小于下一个元素,则增加count数组中相应的字符数。
打印所有字符的计数。
示例
让我们看看代码。
#include输出结果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; }
如果你运行上面的代码,那么你会得到下面的结果。
7 6 5 4 3 2 1 0
结论
如果您对本教程有任何疑问,请在评论部分提及。