Description Link to heading

1138.alphabet-board-path

Solution Link to heading

Hash table.

Notice that we shouldn’t go left then go down or go right then go up.

Code Link to heading

class Solution {
public:
    string alphabetBoardPath(string target) {
        string res;
        vector<int> cur_loc{0, 0};
        vector<int> target_loc{0, 0};
        // 要注意边缘的存在
        for (auto &c : target) {
            target_loc[0] = (c - 'a') / 5;
            target_loc[1] = (c - 'a') % 5;
            int move_row = target_loc[0] - cur_loc[0];
            int move_col = target_loc[1] - cur_loc[1];
            cur_loc[0] = target_loc[0];
            cur_loc[1] = target_loc[1];
            if (move_col < 0) {
                res.insert(res.end(), -move_col, 'L');
                if (move_row >= 0)
                    res.insert(res.end(), move_row, 'D');
                else
                    res.insert(res.end(), -move_row, 'U');
            } else {
                if (move_row >= 0)
                    res.insert(res.end(), move_row, 'D');
                else
                    res.insert(res.end(), -move_row, 'U');
                res.insert(res.end(), move_col, 'R');
            }
            res.push_back('!');
        }
        return res;
    }
};