HJ17 坐标移动【牛客网】
文章目录
- 零、原题链接
- 一、题目描述
- 二、测试用例
- 三、解题思路
- 四、参考代码
零、原题链接
HJ17 坐标移动
一、题目描述
二、测试用例
三、解题思路
- 基本思路:
这题的难点在于理解题目和如何处理各种情况。题目是给定一串指令,首先要判断指令是否合法,合法指令要满足三个条件,然后,如果指令合法,则按照指令进行移动。最终得到最后的位置坐标。 - 具体思路:
- 解决输入,可以使用 stringstream 进行字符串分割
- 判断指令是否合法:
- 指令长度只能是
2
或者3
; - 指令除了第一个字符,其他字符只能为数字;【如果合法顺便将字符串转为整型】
- 指令第一个字符只能是
'W'
,'A'
,'S'
,'D'
。【如果合法则进行移动】
- 指令长度只能是
- 处理完所有指令,则输出最终坐标;
四、参考代码
时间复杂度: O ( n ) \Omicron(n) O(n)【n 是指令序列长度】
空间复杂度: O ( n ) \Omicron(n) O(n)
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;int main() {stringstream ss;string str;cin >> str;ss << str;int x = 0, y = 0;while (getline(ss, str, ';')) {if (str.length() != 2 && str.length() != 3)continue;int num = 0;if (str.length() == 3 && isdigit(str[1]) && isdigit(str[2])) {num += (str[1] - '0') * 10 + str[2] - '0';} else if (str.length() == 2 && isdigit(str[1])) {num += str[1] - '0';} else {continue;}if (str[0] == 'W') {y += num;} else if (str[0] == 'A') {x -= num;} else if (str[0] == 'S') {y -= num;} else if (str[0] == 'D') {x += num;}}cout << x << ',' << y;
}
// 64 位输出请用 printf("%lld")