Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จำนวนสมาชิกที่มากกว่าด้านขวาในสตริง C++


ให้สตริง นับจำนวนตัวอักษรที่มากกว่า (larger) อยู่ด้านขวาของแต่ละตัวอักษร

ตัวอย่าง:

Input: "abc"
Output: 2 1 0

'a' มีตัวมากกว่าด้านขวา 2 ตัว (b,c), 'b' มี 1 ตัว (c), 'c' มี 0

อัลกอริทึม

  • กำหนดสตริงและอาเรย์ count
  • วนลูป 2 ชั้น i, j (j > i):
    • ถ้า str[i] < str[j] count[i]++
  • พิมพ์ count ทั้งหมด

การเขียนโปรแกรม 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; }

ผลลัพธ์

7 6 5 4 3 2 1 0