2120.执行所有后缀指令
链接:2120.执行所有后缀指令
难度:Medium
标签:字符串、模拟
简介:返回一个长度为 m 的数组 answer ,其中 answer[i] 是机器人从第 i 条指令 开始 ,可以执行的 指令数目 。
题解 1 - cpp
- 编辑时间:2021-12-31
- 执行用时:36ms
- 内存消耗:10.2MB
- 编程语言:cpp
- 解法介绍:模拟。
class Solution {
   public:
    int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    int getDirIdx(char ch) {
        if (ch == 'D') return 0;
        if (ch == 'U') return 1;
        if (ch == 'R') return 2;
        if (ch == 'L') return 3;
        return -1;
    }
    vector<int> executeInstructions(int n, vector<int>& startPos, string s) {
        vector<int> ans;
        int n_str = s.size();
        for (int i = 0; i < n_str; i++) {
            int cnt = 0, row = startPos[0], col = startPos[1];
            for (int j = i; j < n_str; j++, cnt++) {
                int diridx = getDirIdx(s[j]);
                row += dirs[diridx][0];
                col += dirs[diridx][1];
                if (row < 0 || row >= n || col < 0 || col >= n) break;
            }
            ans.push_back(cnt);
        }
        return ans;
    }
};