牛客华为机试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)
标签:distance,direction,word,String,HJ17,牛客,import,机试,dis 来源: https://www.cnblogs.com/junstat/p/16094009.html