กำหนด string s ประกอบด้วย 'L' (ซ้าย), 'R' (ขวา), '?' (ซ้ายหรือขวา) เริ่มจากตำแหน่ง 0 หาระยะห่างสูงสุดจากจุดกำเนิดที่เป็นไปได้โดยแทนที่ '?' ด้วย 'L' หรือ 'R'
ตัวอย่าง: "LLRRL??" → Output: 3
คำอธิบาย: นับ L=3, R=2, ?=2 → max(3,2) - min(3,2) + 2 = 3 - 2 + 2 = 3
วิธีแก้ปัญหา
- นับจำนวน
L,R,? - ระยะห่างสูงสุด =
|L - R| + ?(เลือกแทน ? ทั้งหมดให้เป็นทิศทางที่มีมากกว่า)
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(string s) {
int op = 0, l = 0, r = 0;
for(char c : s) {
if(c == 'L') l++;
else if(c == 'R') r++;
else op++;
}
return max(l, r) - min(l, r) + op;
}
};
int main() {
Solution ob;
cout << ob.solve("LLRRL??");
}
Input
"LLRRL??"
Output
3