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

โค้ด C++ นับ Volume ของข้อความ

โจทย์: สตริง S คั่นด้วยช่องว่าง Volume ของคำ = จำนวนตัวพิมพ์ใหญ่ในคำนั้น Volume ของข้อความ = Volume สูงสุดของทุกคำ

Input: "Paper MILL" → Output: 4 (คำว่า MILL มีตัวพิมพ์ใหญ่ 4 ตัว)

ขั้นตอนแก้

ans := 0, a := 0
for each char s in S:
    if 'A' <= s <= 'Z': a++
    if s == ' ':
        ans = max(ans, a)
        a = 0
ans = max(ans, a)
return ans

ตัวอย่างโค้ด

#include <bits/stdc++.h>
using namespace std;
int solve(string S) {
    int ans = 0, a = 0, n = S.size();
    for (int i = 0; i <= n; i++) {
        char s = S[i];
        if (s >= 'A' && s <= 'Z') a++;
        if (s == ' ') {
            ans = max(ans, a);
            a = 0;
        }
    }
    ans = max(ans, a);
    return ans;
}
int main() {
    string S = "Paper MILL";
    cout << solve(S) << endl;
}

Input

"Paper MILL"

Output

4