📖方法一
思路
只需要根据 commands 中的命令进行数学运算就可以了。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| #include <string> class Solution { public: int finalPositionOfSnake(int n, vector<string>& commands) { int endLocation = 0; for (int i = 0; i < commands.size(); i++) { string command = commands[i]; if (command == "UP") { endLocation -= n; } else if (command == "DOWN") { endLocation += n; } else if (command == "LEFT") { endLocation -= 1; } else if (command == "RIGHT") { endLocation += 1; } } return endLocation; } };
|
收获
- 学会了遍历 string 类型数组的方法。