解題思路
由 (0,0) 開始,R使x加1、L使x減1、U使y加1、D使y減1。
依序更新或分別計算兩方向的出現次數差;每一步位移相加就是終點座標。
時間 O(|S|),字串空間 O(|S|),額外 O(1)。
Step-by-step animation
教學例子:教學指令 RUL,先R到 (1,0)。
步驟 1 / 3
步驟 1
教學指令 RUL,先R到 (1,0)。
R
- 狀態
- 1 0
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
cin >> s;
int x = 0, y = 0;
for (char c : s) {
x += (c == 'R') - (c == 'L');
y += (c == 'U') - (c == 'D');
}
cout << x << ' ' << y << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。