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

โค้ด C++ หาความยาวสตริงทิศทางหุ่นยนต์หลังลดรูป

โจทย์: สตริง S ประกอบ 'R' (ขวา) และ 'U' (บน) แทนการเคลื่อนที่หุ่นยนต์ คู่ "RU" หรือ "UR" แทนที่ด้วย "D" (เฉียง) หาความยาวสตริงหลังลดรูป

Input: S="RUURU" → Output: 3 (ลดรูปเป็น "DUD")

ขั้นตอนแก้

ans := 0
for i := 0 to n-1:
    if S[i] != S[i+1]: i++
    ans++
return ans

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

#include <bits/stdc++.h>
using namespace std;
int solve(string S) {
    int ans = 0, n = S.size();
    for (int i = 0; i < n; ++i) {
        if (S[i] != S[i+1]) i++;
        ans++;
    }
    return ans;
}
int main() {
    string S = "RUURU";
    cout << solve(S) << endl;
}

Input

"RUURU"

Output

3