学习记录
2025.3.15
题目:
思路:按照题目对i,j进行加减。
解题步骤:
1。 变量初始化:i 和 j 初始值都为 0。它们将根据命令进行更新。
2.遍历命令。
3. 处理每个命令:s.charAt(0) 获取当前命令字符串的第一个字符,用于判断命令类型。switch 语句根据命令的第一个字符来决定如何更新 i 和 j:
‘U’:i 减 1(向上移动)。‘D’:i 加 1(向下移动)。‘L’:j 减 1(向左移动)。默认情况(即其他字符):j 加 1(向右移动)。
4. 返回结果。
代码:
int finalPositionOfSnake(int n, char** commands, int commandsSize) {int ans = 0;for (int i = 0; i < commandsSize; i++) {if (commands[i][0] == 'U') {ans -= n;} else if (commands[i][0] == 'D') {ans += n;} else if (commands[i][0] == 'L') {ans--;} else {ans++;}}return ans;
}
class Solution {public int finalPositionOfSnake(int n, List<String> commands) {int i = 0;int j = 0;for (String s : commands) {switch (s.charAt(0)) {case 'U' -> i--;case 'D' -> i++;case 'L' -> j--;default -> j++;}}return i * n + j;}
}
复杂度:
N(N)
N(1)