牛客华为机试HJ17
2022/4/2 23:21:13
本文主要是介绍牛客华为机试HJ17,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
原题传送门
1. 问题描述
2. Solution
1、思路
注意条件过滤
2、实现
Java
package huawei.HJ017; import java.io.IOException; import java.nio.file.Paths; import java.util.Scanner; import java.util.regex.Pattern; public class Main { static Scanner in; public static void main(String[] args) throws IOException { if (!"Linux".equals(System.getProperty("os.name"))) { in = new Scanner(Paths.get("/Users/jun/Documents/Learn/JavaLearning/NowCoder/src/huawei/HJ017/input.txt")); } else { in = new Scanner(System.in); } while (in.hasNext()) { String s = in.nextLine(); solve(s); } } private static void solve(String s) { int x = 0; int y = 0; for (String word : s.split(";")) { if (word.length() == 0 || word.length() > 3) continue; char direction = word.charAt(0); String distance = word.substring(1); if ((direction != 'A' && direction != 'S' && direction != 'W' && direction != 'D') || (!isNumber(distance))) continue; int dis = Integer.parseInt(distance); if (direction == 'A') x -= dis; else if (direction == 'D') x += dis; else if (direction == 'W') y += dis; else if (direction == 'S') y -= dis; } System.out.printf("%d,%d", x, y); } private static boolean isNumber(String s) { Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); return pattern.matcher(s).matches(); } }
Python
import sys if sys.platform != "linux": file_in = open("input/HJ17.txt") sys.stdin = file_in def solve(s): x, y = 0, 0 for word in s.split(";"): if not word or len(word) > 3: continue direction = word[0] distance = word[1:] if not distance.isdigit() or len(distance) > 2: continue distance = int(distance) if direction == 'A': x -= distance elif direction == 'D': x += distance elif direction == 'W': y += distance elif direction == 'S': y -= distance print(f'{x},{y}') for line in sys.stdin: solve(line.strip())
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(1)
这篇关于牛客华为机试HJ17的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28AI给的和自己写的Python代码,都无法改变输入框的内容,替换也不行
- 2024-09-27Sentinel配置限流资料:新手入门教程
- 2024-09-27Sentinel配置限流资料详解
- 2024-09-27Sentinel限流资料:新手入门教程
- 2024-09-26Sentinel限流资料入门详解
- 2024-09-26Springboot框架资料:初学者入门教程
- 2024-09-26Springboot框架资料详解:新手入门教程
- 2024-09-26Springboot企业级开发资料:新手入门指南
- 2024-09-26SpringBoot企业级开发资料新手指南
- 2024-09-26Springboot微服务资料入门教程